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

rename packages to com.graphhopper.* - #215

This commit is contained in:
oblonski 2016-02-03 14:31:36 +01:00
parent 2f4e9196d9
commit 8004676211
465 changed files with 3569 additions and 3567 deletions

View file

@ -0,0 +1,180 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.FleetSize;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Reader that reads the well-known solomon-instances.
*
* <p>See: <a href="http://neo.lcc.uma.es/vrp/vrp-instances/capacitated-vrp-with-time-windows-instances/">neo.org</a>
*
* @author stefan
*
*/
public class BelhaizaReader {
private int fixedCosts;
/**
* @param costProjectionFactor the costProjectionFactor to set
*/
public void setVariableCostProjectionFactor(double costProjectionFactor) {
this.variableCostProjectionFactor = costProjectionFactor;
}
private static Logger logger = LogManager.getLogger(BelhaizaReader.class);
private final VehicleRoutingProblem.Builder vrpBuilder;
private double coordProjectionFactor = 1;
private double timeProjectionFactor = 1;
private double variableCostProjectionFactor = 1;
private double fixedCostPerVehicle = 0.0;
public BelhaizaReader(VehicleRoutingProblem.Builder vrpBuilder) {
super();
this.vrpBuilder = vrpBuilder;
}
public BelhaizaReader(VehicleRoutingProblem.Builder vrpBuilder, double fixedCostPerVehicle) {
super();
this.vrpBuilder = vrpBuilder;
this.fixedCostPerVehicle=fixedCostPerVehicle;
}
public void read(String solomonFile){
vrpBuilder.setFleetSize(FleetSize.INFINITE);
BufferedReader reader = getReader(solomonFile);
int vehicleCapacity = 0;
int counter = 0;
String line;
while((line = readLine(reader)) != null){
String[] tokens = line.replace("\r", "").trim().split("\\s+");
counter++;
if(counter == 2){
vehicleCapacity = Integer.parseInt(tokens[1]);
continue;
}
if(counter > 2){
if(tokens.length < 7) continue;
Coordinate coord = makeCoord(tokens[1],tokens[2]);
String customerId = tokens[0];
int demand = Integer.parseInt(tokens[4]);
double serviceTime = Double.parseDouble(tokens[3])*timeProjectionFactor;
if(counter == 3){
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("solomonType").addCapacityDimension(0, vehicleCapacity);
typeBuilder.setCostPerDistance(1.0*variableCostProjectionFactor).setFixedCost(fixedCostPerVehicle)
.setCostPerWaitingTime(0.8);
System.out.println("fix: " + fixedCostPerVehicle + "; perDistance: 1.0; perWaitingTime: 0.8");
VehicleTypeImpl vehicleType = typeBuilder.build();
double end = Double.parseDouble(tokens[8])*timeProjectionFactor;
for(int i=0;i<10;i++) {
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("solomonVehicle"+(i+1)).setEarliestStart(0.).setLatestArrival(end)
.setStartLocation(Location.Builder.newInstance().setId(customerId)
.setCoordinate(coord).build()).setType(vehicleType).build();
vrpBuilder.addVehicle(vehicle);
}
}
else{
Service.Builder serviceBuilder = Service.Builder.newInstance(customerId);
serviceBuilder.addSizeDimension(0, demand).setLocation(Location.Builder.newInstance().setCoordinate(coord).setId(customerId).build()).setServiceTime(serviceTime);
int noTimeWindows = Integer.parseInt(tokens[7]);
for(int i=0;i<noTimeWindows*2;i=i+2){
double earliest = Double.parseDouble(tokens[8+i]);
double latest = Double.parseDouble(tokens[8+i+1]);
serviceBuilder.addTimeWindow(earliest,latest);
}
vrpBuilder.addJob(serviceBuilder.build());
}
}
}
close(reader);
}
public void setCoordProjectionFactor(double coordProjectionFactor) {
this.coordProjectionFactor = coordProjectionFactor;
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(e);
System.exit(1);
}
}
private String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
logger.error(e);
System.exit(1);
return null;
}
}
private Coordinate makeCoord(String xString, String yString) {
double x = Double.parseDouble(xString);
double y = Double.parseDouble(yString);
return new Coordinate(x*coordProjectionFactor,y*coordProjectionFactor);
}
private BufferedReader getReader(String solomonFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(solomonFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
logger.error(e1);
System.exit(1);
}
return reader;
}
public void setTimeProjectionFactor(double timeProjection) {
this.timeProjectionFactor=timeProjection;
}
public void setFixedCosts(int fixedCosts) {
this.fixedCostPerVehicle = fixedCosts;
}
}

View file

@ -0,0 +1,137 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.FleetSize;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Reader that reads Christophides, Mingozzi and Toth instances.
* <p/>
* <p>Files and file-description can be found <a href="http://neo.lcc.uma.es/vrp/vrp-instances/capacitated-vrp-instances/">here</a>.
*
* @author stefan schroeder
*/
public class ChristofidesReader {
private static Logger logger = LogManager.getLogger(ChristofidesReader.class);
private final VehicleRoutingProblem.Builder vrpBuilder;
private double coordProjectionFactor = 1;
/**
* Constructs the reader.
*
* @param vrpBuilder the builder
*/
public ChristofidesReader(VehicleRoutingProblem.Builder vrpBuilder) {
super();
this.vrpBuilder = vrpBuilder;
}
/**
* Reads instance-file and memorizes vehicles, customers and so forth in
* {@link VehicleRoutingProblem.Builder}.
*
* @param fileName the filename to read
*/
public void read(String fileName) {
vrpBuilder.setFleetSize(FleetSize.INFINITE);
BufferedReader reader = getReader(fileName);
int vehicleCapacity = 0;
double serviceTime = 0.0;
double endTime = Double.MAX_VALUE;
int counter = 0;
String line;
while ((line = readLine(reader)) != null) {
line = line.replace("\r", "");
line = line.trim();
String[] tokens = line.split(" ");
if (counter == 0) {
vehicleCapacity = Integer.parseInt(tokens[1].trim());
endTime = Double.parseDouble(tokens[2].trim());
serviceTime = Double.parseDouble(tokens[3].trim());
} else if (counter == 1) {
Coordinate depotCoord = makeCoord(tokens[0].trim(), tokens[1].trim());
VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance("christophidesType").addCapacityDimension(0, vehicleCapacity).
setCostPerDistance(1.0).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("christophidesVehicle").setLatestArrival(endTime).setStartLocation(Location.newInstance(depotCoord.getX(), depotCoord.getY())).
setType(vehicleType).build();
vrpBuilder.addVehicle(vehicle);
} else {
Coordinate customerCoord = makeCoord(tokens[0].trim(), tokens[1].trim());
int demand = Integer.parseInt(tokens[2].trim());
String customer = Integer.valueOf(counter - 1).toString();
Service service = Service.Builder.newInstance(customer).addSizeDimension(0, demand).setServiceTime(serviceTime).setLocation(Location.newInstance(customerCoord.getX(), customerCoord.getY())).build();
vrpBuilder.addJob(service);
}
counter++;
}
close(reader);
}
public void setCoordProjectionFactor(double coordProjectionFactor) {
this.coordProjectionFactor = coordProjectionFactor;
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Coordinate makeCoord(String xString, String yString) {
double x = Double.parseDouble(xString);
double y = Double.parseDouble(yString);
return new Coordinate(x * coordProjectionFactor, y * coordProjectionFactor);
}
private BufferedReader getReader(String solomonFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(solomonFile));
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
}
return reader;
}
}

View file

@ -0,0 +1,166 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.FleetSize;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl.Builder;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Reader that reads instances developed by:
* <p/>
* <p>Cordeau, J.-F., Gendreau, M. and Laporte, G. (1997), A tabu search heuristic for periodic and multi-depot vehicle routing problems.
* Networks, 30: 105119. doi: 10.1002/(SICI)1097-0037(199709)30:2<105::AID-NET5>3.0.CO;2-G
* <p/>
* <p>Files and file-description can be found <a href="http://neo.lcc.uma.es/vrp/vrp-instances/multiple-depot-vrp-instances/">here</a>.
*
* @author stefan schroeder
*/
public class CordeauReader {
private static Logger logger = LogManager.getLogger(CordeauReader.class);
private final VehicleRoutingProblem.Builder vrpBuilder;
private double coordProjectionFactor = 1;
public CordeauReader(VehicleRoutingProblem.Builder vrpBuilder) {
super();
this.vrpBuilder = vrpBuilder;
}
@Deprecated
public CordeauReader(VehicleRoutingProblem.Builder vrpBuilder, boolean penaltyVehicles) {
super();
this.vrpBuilder = vrpBuilder;
}
public void read(String fileName) {
vrpBuilder.setFleetSize(FleetSize.FINITE);
BufferedReader reader = getReader(fileName);
int vrpType;
int nOfDepots = 0;
int nOfCustomers = 0;
int nOfVehiclesAtEachDepot = 0;
int counter = 0;
String line;
List<List<Builder>> vehiclesAtDepot = new ArrayList<List<Builder>>();
int depotCounter = 0;
while ((line = readLine(reader)) != null) {
line = line.replace("\r", "");
line = line.trim();
String[] tokens = line.split("\\s+");
if (counter == 0) {
vrpType = Integer.parseInt(tokens[0].trim());
if (vrpType != 2)
throw new IllegalStateException("expect vrpType to be equal to 2 and thus to be MDVRP");
nOfVehiclesAtEachDepot = Integer.parseInt(tokens[1].trim());
nOfCustomers = Integer.parseInt(tokens[2].trim());
nOfDepots = Integer.parseInt(tokens[3].trim());
} else if (counter <= nOfDepots) {
String depot = Integer.valueOf(counter).toString();
int duration = Integer.parseInt(tokens[0].trim());
if (duration == 0) duration = 999999;
int capacity = Integer.parseInt(tokens[1].trim());
VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance(counter + "_cordeauType").addCapacityDimension(0, capacity).
setCostPerDistance(1.0).setFixedCost(0).build();
List<Builder> builders = new ArrayList<VehicleImpl.Builder>();
for (int vehicleCounter = 0; vehicleCounter < nOfVehiclesAtEachDepot; vehicleCounter++) {
Builder vBuilder = VehicleImpl.Builder.newInstance(depot + "_" + (vehicleCounter + 1) + "_cordeauVehicle");
vBuilder.setLatestArrival(duration).setType(vehicleType);
builders.add(vBuilder);
}
vehiclesAtDepot.add(builders);
} else if (counter <= (nOfCustomers + nOfDepots)) {
String id = tokens[0].trim();
Coordinate customerCoord = makeCoord(tokens[1].trim(), tokens[2].trim());
double serviceTime = Double.parseDouble(tokens[3].trim());
int demand = Integer.parseInt(tokens[4].trim());
Service service = Service.Builder.newInstance(id).addSizeDimension(0, demand).setServiceTime(serviceTime)
.setLocation(Location.Builder.newInstance().setId(id).setCoordinate(customerCoord).build()).build();
vrpBuilder.addJob(service);
} else if (counter <= (nOfCustomers + nOfDepots + nOfDepots)) {
Coordinate depotCoord = makeCoord(tokens[1].trim(), tokens[2].trim());
List<Builder> vBuilders = vehiclesAtDepot.get(depotCounter);
for (Builder vBuilder : vBuilders) {
vBuilder.setStartLocation(Location.newInstance(depotCoord.getX(), depotCoord.getY()));
VehicleImpl vehicle = vBuilder.build();
vrpBuilder.addVehicle(vehicle);
}
depotCounter++;
} else {
throw new IllegalStateException("there are more lines than expected in file.");
}
counter++;
}
close(reader);
}
public void setCoordProjectionFactor(double coordProjectionFactor) {
this.coordProjectionFactor = coordProjectionFactor;
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Coordinate makeCoord(String xString, String yString) {
double x = Double.parseDouble(xString);
double y = Double.parseDouble(yString);
return new Coordinate(x * coordProjectionFactor, y * coordProjectionFactor);
}
private BufferedReader getReader(String solomonFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(solomonFile));
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
}
return reader;
}
}

View file

@ -0,0 +1,221 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import com.graphhopper.jsprit.core.problem.driver.Driver;
import com.graphhopper.jsprit.core.problem.vehicle.Vehicle;
import com.graphhopper.jsprit.core.util.EuclideanDistanceCalculator;
import com.graphhopper.jsprit.core.util.Locations;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Figliozzi {
public static class TimeDependentTransportCostsFactory {
public static enum SpeedDistribution {
TD1a, TD1b, TD1c, TD2a, TD2b, TD2c, TD3a, TD3b, TD3c, TD1d, TD2d, TD3d, TD4, TD5, TD6, CLASSIC
}
public static TDCosts createCosts(Locations locations, SpeedDistribution speedDistribution, double depotClosingTime) {
List<Double> timeBins = createTimeBins(depotClosingTime);
List<Double> speedValues = createSpeedValues(speedDistribution);
return new TDCosts(locations, timeBins, speedValues);
}
static List<Double> createSpeedValues(SpeedDistribution speedDistribution) {
List<Double> speedValues = Collections.emptyList();
switch (speedDistribution) {
case TD1a:
speedValues = Arrays.asList(1., 1.6, 1.05, 1.6, 1.);
break;
case TD2a:
speedValues = Arrays.asList(1., 2., 1.5, 2., 1.);
break;
case TD3a:
speedValues = Arrays.asList(1., 2.5, 1.75, 2.5, 1.);
break;
case TD1b:
speedValues = Arrays.asList(1.6, 1., 1.05, 1., 1.6);
break;
case TD2b:
speedValues = Arrays.asList(2., 1., 1.5, 1., 2.);
break;
case TD3b:
speedValues = Arrays.asList(2.5, 1., 1.75, 1., 2.5);
break;
case TD1c:
speedValues = Arrays.asList(1.6, 1.6, 1.05, 1., 1.);
break;
case TD2c:
speedValues = Arrays.asList(2., 2., 1.5, 1., 1.);
break;
case TD3c:
speedValues = Arrays.asList(2.5, 2.5, 1.75, 1., 1.);
break;
case TD1d:
speedValues = Arrays.asList(1., 1., 1.05, 1.6, 1.6);
break;
case TD2d:
speedValues = Arrays.asList(1., 1., 1.5, 2., 2.);
break;
case TD3d:
speedValues = Arrays.asList(1., 1., 1.75, 2.5, 2.5);
break;
case TD4:
speedValues = Arrays.asList(1.1, 0.85, 1.1, 0.85, 1.1);
break;
case TD5:
speedValues = Arrays.asList(1.2, 0.8, 1., 0.8, 1.2);
break;
case TD6:
speedValues = Arrays.asList(1.2, 0.7, 1.2, 0.7, 1.2);
break;
case CLASSIC:
speedValues = Arrays.asList(1., 1., 1., 1., 1.);
break;
}
return speedValues;
}
private static List<Double> createTimeBins(double depotClosingTime) {
List<Double> timeBins = new ArrayList<Double>();
timeBins.add(.2 * depotClosingTime);
timeBins.add(.4 * depotClosingTime);
timeBins.add(.6 * depotClosingTime);
timeBins.add(.8 * depotClosingTime);
timeBins.add(depotClosingTime);
return timeBins;
}
}
public static class TDCosts implements VehicleRoutingTransportCosts {
private List<Double> timeBins;
private List<Double> speed;
private Locations locations;
private double transportDistanceParameter = 1.;
private double transportTimeParameter = 1.;
public TDCosts(Locations locations, List<Double> timeBins, List<Double> speedValues) {
super();
speed = speedValues;
this.timeBins = timeBins;
this.locations = locations;
}
public void setTransportDistanceParameter(double transportDistanceParameter) {
this.transportDistanceParameter = transportDistanceParameter;
}
public void setTransportTimeParameter(double transportTimeParameter) {
this.transportTimeParameter = transportTimeParameter;
}
@Override
public double getTransportCost(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) {
return transportDistanceParameter * EuclideanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId())) +
transportTimeParameter * getTransportTime(from, to, departureTime, driver, vehicle);
}
@Override
public double getBackwardTransportCost(Location from, Location to, double arrivalTime, Driver driver, Vehicle vehicle) {
return transportDistanceParameter * EuclideanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId())) +
transportTimeParameter * getBackwardTransportTime(from, to, arrivalTime, driver, vehicle);
}
@Override
public double getTransportTime(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) {
if (from.equals(to)) {
return 0.0;
}
double totalTravelTime = 0.0;
double distanceToTravel = EuclideanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId()));
double currentTime = departureTime;
for (int i = 0; i < timeBins.size(); i++) {
double timeThreshold = timeBins.get(i);
if (currentTime < timeThreshold) {
double maxReachableDistance = (timeThreshold - currentTime) * speed.get(i);
if (distanceToTravel > maxReachableDistance) {
distanceToTravel = distanceToTravel - maxReachableDistance;
totalTravelTime += (timeThreshold - currentTime);
currentTime = timeThreshold;
} else { //<= maxReachableDistance
totalTravelTime += distanceToTravel / speed.get(i);
return totalTravelTime;
}
}
}
return Double.MAX_VALUE;
}
@Override
public double getBackwardTransportTime(Location from, Location to, double arrivalTime, Driver driver, Vehicle vehicle) {
if (from.equals(to)) {
return 0.0;
}
double totalTravelTime = 0.0;
double distanceToTravel = EuclideanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId()));
double currentTime = arrivalTime;
for (int i = timeBins.size() - 1; i >= 0; i--) {
double nextLowerTimeThreshold;
if (i > 0) {
nextLowerTimeThreshold = timeBins.get(i - 1);
} else {
nextLowerTimeThreshold = 0;
}
if (currentTime > nextLowerTimeThreshold) {
double maxReachableDistance = (currentTime - nextLowerTimeThreshold) * speed.get(i);
if (distanceToTravel > maxReachableDistance) {
distanceToTravel = distanceToTravel - maxReachableDistance;
totalTravelTime += (currentTime - nextLowerTimeThreshold);
currentTime = nextLowerTimeThreshold;
} else { //<= maxReachableDistance
totalTravelTime += distanceToTravel / speed.get(i);
return totalTravelTime;
}
}
}
return Double.MAX_VALUE;
}
}
}

View file

@ -0,0 +1,205 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder;
import com.graphhopper.jsprit.core.problem.job.Shipment;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* test instances for the capacitated vrp with pickup and deliveries and time windows.
* instances are from li and lim and can be found at:
* http://www.top.sintef.no/vrp/benchmarks.html
*
* @author stefan schroeder
*/
public class LiLimReader {
static class CustomerData {
public Coordinate coord;
public double start;
public double end;
public double serviceTime;
public CustomerData(Coordinate coord, double start, double end, double serviceTime) {
super();
this.coord = coord;
this.start = start;
this.end = end;
this.serviceTime = serviceTime;
}
}
static class Relation {
public String from;
public String to;
public int demand;
public Relation(String from, String to, int demand) {
super();
this.from = from;
this.to = to;
this.demand = demand;
}
}
private static Logger logger = LogManager.getLogger(LiLimReader.class);
private VehicleRoutingProblem.Builder vrpBuilder;
private int vehicleCapacity;
private String depotId;
private Map<String, CustomerData> customers;
private Collection<Relation> relations;
private double depotOpeningTime;
private double depotClosingTime;
private int fixCosts = 0;
public LiLimReader(Builder vrpBuilder) {
customers = new HashMap<String, LiLimReader.CustomerData>();
relations = new ArrayList<LiLimReader.Relation>();
this.vrpBuilder = vrpBuilder;
}
public LiLimReader(Builder builder, int fixCosts) {
customers = new HashMap<String, LiLimReader.CustomerData>();
relations = new ArrayList<LiLimReader.Relation>();
this.vrpBuilder = builder;
this.fixCosts = fixCosts;
}
public void read(String filename) {
readShipments(filename);
buildShipments();
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0, vehicleCapacity)
.setCostPerDistance(1.0).setFixedCost(fixCosts).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle")
.setEarliestStart(depotOpeningTime).setLatestArrival(depotClosingTime)
.setStartLocation(Location.Builder.newInstance().setCoordinate(customers.get(depotId).coord).build()).setType(type).build();
vrpBuilder.addVehicle(vehicle);
}
private void buildShipments() {
Integer counter = 0;
for (Relation rel : relations) {
counter++;
String from = rel.from;
String to = rel.to;
int demand = rel.demand;
Shipment s = Shipment.Builder.newInstance(counter.toString()).addSizeDimension(0, demand)
.setPickupLocation(Location.Builder.newInstance().setCoordinate(customers.get(from).coord).build()).setPickupServiceTime(customers.get(from).serviceTime)
.setPickupTimeWindow(TimeWindow.newInstance(customers.get(from).start, customers.get(from).end))
.setDeliveryLocation(Location.Builder.newInstance().setCoordinate(customers.get(to).coord).build()).setDeliveryServiceTime(customers.get(to).serviceTime)
.setDeliveryTimeWindow(TimeWindow.newInstance(customers.get(to).start, customers.get(to).end)).build();
vrpBuilder.addJob(s);
}
}
private BufferedReader getReader(String file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
}
return reader;
}
private void readShipments(String file) {
BufferedReader reader = getReader(file);
String line = null;
boolean firstLine = true;
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\r", "");
line = line.trim();
String[] tokens = line.split("\t");
if (firstLine) {
int vehicleCapacity = getInt(tokens[1]);
this.vehicleCapacity = vehicleCapacity;
firstLine = false;
continue;
} else {
String customerId = tokens[0];
Coordinate coord = makeCoord(tokens[1], tokens[2]);
int demand = getInt(tokens[3]);
double startTimeWindow = getDouble(tokens[4]);
double endTimeWindow = getDouble(tokens[5]);
double serviceTime = getDouble(tokens[6]);
// vrpBuilder.addLocation(customerId, coord);
customers.put(customerId, new CustomerData(coord, startTimeWindow, endTimeWindow, serviceTime));
if (customerId.equals("0")) {
depotId = customerId;
depotOpeningTime = startTimeWindow;
depotClosingTime = endTimeWindow;
}
if (demand > 0) {
relations.add(new Relation(customerId, tokens[8], demand));
}
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private Coordinate makeCoord(String xString, String yString) {
double x = Double.parseDouble(xString);
double y = Double.parseDouble(yString);
return new Coordinate(x, y);
}
private double getDouble(String string) {
return Double.parseDouble(string);
}
private int getInt(String string) {
return Integer.parseInt(string);
}
}

View file

@ -0,0 +1,110 @@
package com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.util.FastVehicleRoutingTransportCostsMatrix;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by schroeder on 18/02/15.
*/
public class LopezIbanezBlumReader {
private static Logger logger = LogManager.getLogger(LopezIbanezBlumReader.class);
private VehicleRoutingProblem.Builder builder;
public LopezIbanezBlumReader(VehicleRoutingProblem.Builder builder) {
this.builder = builder;
}
public void read(String instanceFile) {
builder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
BufferedReader reader = getReader(instanceFile);
String line;
int noNodes = 0;
int lineCount = 1;
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = null;
while ((line = readLine(reader)) != null) {
if (line.startsWith("#")) continue;
if (lineCount == 1) {
noNodes = Integer.parseInt(line);
matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(noNodes, false);
lineCount++;
continue;
} else if (lineCount <= 1 + noNodes) {
String[] wimaTokens = line.split("\\s+");
int nodeIndex = lineCount - 2;
for (int toIndex = 0; toIndex < wimaTokens.length; toIndex++) {
matrixBuilder.addTransportDistance(nodeIndex, toIndex, Double.parseDouble(wimaTokens[toIndex]));
matrixBuilder.addTransportTime(nodeIndex, toIndex, Double.parseDouble(wimaTokens[toIndex]));
}
lineCount++;
continue;
} else {
int nodeIndex = lineCount - 2 - noNodes;
String[] twTokens = line.split("\\s+");
if (nodeIndex == 0) {
VehicleImpl travelingSalesman = VehicleImpl.Builder.newInstance("traveling_salesman").setStartLocation(Location.newInstance(nodeIndex))
.setEarliestStart(Double.parseDouble(twTokens[0])).setLatestArrival(Double.parseDouble(twTokens[1])).build();
builder.addVehicle(travelingSalesman);
} else {
Service s = Service.Builder.newInstance("" + nodeIndex).setLocation(Location.newInstance(nodeIndex))
.setTimeWindow(TimeWindow.newInstance(Double.parseDouble(twTokens[0]), Double.parseDouble(twTokens[1]))).build();
builder.addJob(s);
}
lineCount++;
}
}
builder.setRoutingCost(matrixBuilder.build());
close(reader);
}
public static void main(String[] args) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
new LopezIbanezBlumReader(builder).read("input/Dumas/n20w20.001.txt");
VehicleRoutingProblem vrp = builder.build();
System.out.println("0->1: " + vrp.getTransportCosts().getTransportCost(Location.newInstance(0), Location.newInstance(1), 0, null, null));
System.out.println("0->20: " + vrp.getTransportCosts().getTransportCost(Location.newInstance(0), Location.newInstance(20), 0, null, null));
System.out.println("4->18: " + vrp.getTransportCosts().getTransportCost(Location.newInstance(4), Location.newInstance(18), 0, null, null));
System.out.println("20->8: " + vrp.getTransportCosts().getTransportCost(Location.newInstance(20), Location.newInstance(8), 0, null, null));
System.out.println("18: " + ((Service) vrp.getJobs().get("" + 18)).getTimeWindow().getStart() + " " + ((Service) vrp.getJobs().get("" + 18)).getTimeWindow().getEnd());
System.out.println("20: " + ((Service) vrp.getJobs().get("" + 20)).getTimeWindow().getStart() + " " + ((Service) vrp.getJobs().get("" + 20)).getTimeWindow().getEnd());
System.out.println("1: " + ((Service) vrp.getJobs().get("" + 1)).getTimeWindow().getStart() + " " + ((Service) vrp.getJobs().get("" + 1)).getTimeWindow().getEnd());
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private BufferedReader getReader(String solomonFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(solomonFile));
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
}
return reader;
}
}

View file

@ -0,0 +1,179 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.FleetSize;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class LuiShenReader {
private static Logger logger = LogManager.getLogger(LuiShenReader.class);
private final VehicleRoutingProblem.Builder vrpBuilder;
private double coordProjectionFactor = 1;
public LuiShenReader(VehicleRoutingProblem.Builder vrpBuilder) {
super();
this.vrpBuilder = vrpBuilder;
}
/**
* Reads input files to build Liu Shen problem.
* <p/>
* <p>The instance-file is a solomon file. The vehicle-file is a
* txt-file that has the following columns:
* <p>Vehicle;Capacity;Cost_a;Cost_b;Cost_c
* <p>Concrete vehicleType:
* <p>A;100;300;60;30
* <p/>
* <p>In the example above, the vehicle-type with typeId A has
* a capacity of 100, and fixed costs of 100 in cost scenario "a",
* 300 in "b" and 30 in "c".
*
* @param instanceFile is a solomon-instance-file
* @param vehicleFile
* @param costScenario is either "a", "b" or "c"
*/
public void read(String instanceFile, String vehicleFile, String costScenario) {
vrpBuilder.setFleetSize(FleetSize.INFINITE);
BufferedReader reader = getReader(instanceFile);
int counter = 0;
String line = null;
while ((line = readLine(reader)) != null) {
line = line.replace("\r", "");
line = line.trim();
String[] tokens = line.split(" +");
counter++;
if (counter > 9) {
if (tokens.length < 7) continue;
Coordinate coord = makeCoord(tokens[1], tokens[2]);
String customerId = tokens[0];
int demand = Integer.parseInt(tokens[3]);
double start = Double.parseDouble(tokens[4]) * coordProjectionFactor;
double end = Double.parseDouble(tokens[5]) * coordProjectionFactor;
double serviceTime = Double.parseDouble(tokens[6]) * coordProjectionFactor;
if (counter == 10) {
createVehicles(vehicleFile, costScenario, customerId, coord, start, end);
} else {
Service service = Service.Builder.newInstance("" + counter).addSizeDimension(0, demand)
.setLocation(Location.Builder.newInstance().setCoordinate(coord).setId(customerId).build()).setServiceTime(serviceTime)
.setTimeWindow(TimeWindow.newInstance(start, end)).build();
vrpBuilder.addJob(service);
}
}
}
close(reader);
}
private void createVehicles(String vehicleFileName, String costScenario, String locationId, Coordinate coord, double start, double end) {
BufferedReader reader = getReader(vehicleFileName);
int costScenarioColumn = getCostScenarioColumn(costScenario);
int vehicleIdColumn = 0;
int capacityColumn = 1;
boolean firstLine = true;
String line = null;
while ((line = readLine(reader)) != null) {
if (firstLine) {
firstLine = false;
continue;
}
String[] tokens = line.split(";");
String vehicleId = tokens[vehicleIdColumn];
int capacity = Integer.parseInt(tokens[capacityColumn]);
int fixCost = Integer.parseInt(tokens[costScenarioColumn]);
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance(vehicleId).addCapacityDimension(0, capacity);
typeBuilder.setFixedCost(fixCost).setCostPerDistance(1.0);
VehicleTypeImpl type = typeBuilder.build();
VehicleImpl reprVehicle = VehicleImpl.Builder.newInstance(vehicleId).setEarliestStart(start).setLatestArrival(end).
setStartLocation(Location.Builder.newInstance().setId(locationId).setCoordinate(coord).build())
.setType(type).build();
vrpBuilder.addVehicle(reprVehicle);
}
close(reader);
}
private int getCostScenarioColumn(String costScenario) {
if (costScenario.equals("a")) {
return 2;
} else if (costScenario.equals("b")) {
return 3;
} else if (costScenario.equals("c")) {
return 4;
}
throw new IllegalStateException("costScenario " + costScenario + " not known");
}
public void setCoordProjectionFactor(double coordProjectionFactor) {
this.coordProjectionFactor = coordProjectionFactor;
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Coordinate makeCoord(String xString, String yString) {
double x = Double.parseDouble(xString);
double y = Double.parseDouble(yString);
return new Coordinate(x * coordProjectionFactor, y * coordProjectionFactor);
}
private BufferedReader getReader(String solomonFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(solomonFile));
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
}
return reader;
}
}

View file

@ -0,0 +1,162 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.FleetSize;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Reader that reads the well-known solomon-instances.
* <p/>
* <p>See: <a href="http://neo.lcc.uma.es/vrp/vrp-instances/capacitated-vrp-with-time-windows-instances/">neo.org</a>
*
* @author stefan
*/
public class SolomonReader {
/**
* @param costProjectionFactor the costProjectionFactor to set
*/
public void setVariableCostProjectionFactor(double costProjectionFactor) {
this.variableCostProjectionFactor = costProjectionFactor;
}
private static Logger logger = LogManager.getLogger(SolomonReader.class);
private final VehicleRoutingProblem.Builder vrpBuilder;
private double coordProjectionFactor = 1;
private double timeProjectionFactor = 1;
private double variableCostProjectionFactor = 1;
private double fixedCostPerVehicle = 0.0;
public SolomonReader(VehicleRoutingProblem.Builder vrpBuilder) {
super();
this.vrpBuilder = vrpBuilder;
}
public SolomonReader(VehicleRoutingProblem.Builder vrpBuilder, double fixedCostPerVehicle) {
super();
this.vrpBuilder = vrpBuilder;
this.fixedCostPerVehicle = fixedCostPerVehicle;
}
public void read(String solomonFile) {
vrpBuilder.setFleetSize(FleetSize.INFINITE);
BufferedReader reader = getReader(solomonFile);
int vehicleCapacity = 0;
int counter = 0;
String line;
while ((line = readLine(reader)) != null) {
line = line.replace("\r", "");
line = line.trim();
String[] tokens = line.split(" +");
counter++;
if (counter == 5) {
vehicleCapacity = Integer.parseInt(tokens[1]);
continue;
}
if (counter > 9) {
if (tokens.length < 7) continue;
Coordinate coord = makeCoord(tokens[1], tokens[2]);
String customerId = tokens[0];
int demand = Integer.parseInt(tokens[3]);
double start = Double.parseDouble(tokens[4]) * timeProjectionFactor;
double end = Double.parseDouble(tokens[5]) * timeProjectionFactor;
double serviceTime = Double.parseDouble(tokens[6]) * timeProjectionFactor;
if (counter == 10) {
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("solomonType").addCapacityDimension(0, vehicleCapacity);
typeBuilder.setCostPerDistance(1.0 * variableCostProjectionFactor).setFixedCost(fixedCostPerVehicle);
VehicleTypeImpl vehicleType = typeBuilder.build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("solomonVehicle").setEarliestStart(start).setLatestArrival(end)
.setStartLocation(Location.Builder.newInstance().setId(customerId)
.setCoordinate(coord).build()).setType(vehicleType).build();
vrpBuilder.addVehicle(vehicle);
} else {
Service service = Service.Builder.newInstance(customerId).addSizeDimension(0, demand)
.setLocation(Location.Builder.newInstance().setCoordinate(coord).setId(customerId).build()).setServiceTime(serviceTime)
.setTimeWindow(TimeWindow.newInstance(start, end)).build();
vrpBuilder.addJob(service);
}
}
}
close(reader);
}
public void setCoordProjectionFactor(double coordProjectionFactor) {
this.coordProjectionFactor = coordProjectionFactor;
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Coordinate makeCoord(String xString, String yString) {
double x = Double.parseDouble(xString);
double y = Double.parseDouble(yString);
return new Coordinate(x * coordProjectionFactor, y * coordProjectionFactor);
}
private BufferedReader getReader(String solomonFile) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(solomonFile));
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
}
return reader;
}
public void setTimeProjectionFactor(double timeProjection) {
this.timeProjectionFactor = timeProjection;
}
}

View file

@ -0,0 +1,89 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.util.VehicleRoutingTransportCostsMatrix;
import java.io.*;
public class TSPLIB95CostMatrixReader {
private VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder;
public TSPLIB95CostMatrixReader(VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder) {
this.costMatrixBuilder = costMatrixBuilder;
}
public void read(String matrixFile) {
BufferedReader reader = getBufferedReader(matrixFile);
String line;
boolean isEdgeWeights = false;
int fromIndex = 0;
while ((line = getLine(reader)) != null) {
if (line.startsWith("EDGE_WEIGHT_SECTION")) {
isEdgeWeights = true;
continue;
}
if (line.startsWith("DEMAND_SECTION")) {
isEdgeWeights = false;
continue;
}
if (isEdgeWeights) {
String[] tokens = line.split("\\s+");
String fromId = "" + (fromIndex + 1);
for (int i = 0; i < tokens.length; i++) {
double distance = Double.parseDouble(tokens[i]);
String toId = "" + (i + 1);
costMatrixBuilder.addTransportDistance(fromId, toId, distance);
costMatrixBuilder.addTransportTime(fromId, toId, distance);
}
fromIndex++;
}
}
close(reader);
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLine(BufferedReader reader) {
String s = null;
try {
s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
private BufferedReader getBufferedReader(String filename) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(filename)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bufferedReader;
}
}

View file

@ -0,0 +1,328 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.vehicle.Vehicle;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import com.graphhopper.jsprit.core.util.FastVehicleRoutingTransportCostsMatrix;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TSPLIB95Reader {
private VehicleRoutingProblem.Builder vrpBuilder;
private boolean switchCoordinates = false;
public void setSwitchCoordinates(boolean switchCoordinates) {
this.switchCoordinates = switchCoordinates;
}
public TSPLIB95Reader(VehicleRoutingProblem.Builder vrpBuilder) {
this.vrpBuilder = vrpBuilder;
}
public void read(String filename) {
BufferedReader reader = getBufferedReader(filename);
String line_;
Coordinate[] coords = null;
int[] demands = null;
Integer capacity = null;
String edgeType = null;
String edgeWeightFormat = null;
List<Integer> depotIds = new ArrayList<Integer>();
boolean isCoordSection = false;
boolean isDemandSection = false;
boolean isDepotSection = false;
boolean isEdgeWeightSection = false;
List<Double> edgeWeights = new ArrayList<Double>();
int dimensions = 0;
int coordIndex = 0;
Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
while ((line_ = getLine(reader)) != null) {
String line = line_.trim();
if (line.startsWith("EOF") || line.contains("EOF")) {
break;
}
if (line.startsWith("DIMENSION")) {
String[] tokens = line.split(":");
String dim = tokens[1].trim();
dimensions = Integer.parseInt(dim);
coords = new Coordinate[dimensions];
demands = new int[dimensions];
continue;
}
if (line.startsWith("CAPACITY")) {
String[] tokens = line.trim().split(":");
capacity = Integer.parseInt(tokens[1].trim());
continue;
}
if (line.startsWith("EDGE_WEIGHT_TYPE")) {
String[] tokens = line.trim().split(":");
edgeType = tokens[1].trim();
continue;
}
if (line.startsWith("EDGE_WEIGHT_FORMAT")) {
String[] tokens = line.trim().split(":");
edgeWeightFormat = tokens[1].trim();
continue;
}
if (line.startsWith("NODE_COORD_SECTION")) {
isCoordSection = true;
isDemandSection = false;
isDepotSection = false;
isEdgeWeightSection = false;
continue;
}
if (line.startsWith("DEMAND_SECTION")) {
isDemandSection = true;
isCoordSection = false;
isDepotSection = false;
isEdgeWeightSection = false;
continue;
}
if (line.startsWith("DEPOT_SECTION")) {
isDepotSection = true;
isDemandSection = false;
isCoordSection = false;
isEdgeWeightSection = false;
continue;
}
if (line.startsWith("EDGE_WEIGHT_SECTION")) {
isDepotSection = false;
isCoordSection = false;
isDemandSection = false;
isEdgeWeightSection = true;
continue;
}
if (line.startsWith("DISPLAY_DATA_SECTION")) {
isDepotSection = false;
isCoordSection = true;
isDemandSection = false;
isEdgeWeightSection = false;
continue;
}
if (isCoordSection) {
if (coords == null) throw new IllegalStateException("DIMENSION tag missing");
String[] tokens = line.trim().split("\\s+");
Integer id = Integer.parseInt(tokens[0]);
if (switchCoordinates) {
coords[coordIndex] = Coordinate.newInstance(Double.parseDouble(tokens[2]), Double.parseDouble(tokens[1]));
} else
coords[coordIndex] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]));
indexMap.put(id, coordIndex);
coordIndex++;
continue;
}
if (isDemandSection) {
if (demands == null) throw new IllegalStateException("DIMENSION tag missing");
String[] tokens = line.trim().split("\\s+");
Integer id = Integer.parseInt(tokens[0]);
int index = indexMap.get(id);
demands[index] = Integer.parseInt(tokens[1]);
continue;
}
if (isDepotSection) {
if (line.equals("-1")) {
isDepotSection = false;
} else {
depotIds.add(Integer.parseInt(line));
}
continue;
}
if (isEdgeWeightSection) {
String[] tokens = line.trim().split("\\s+");
for (String s : tokens) edgeWeights.add(Double.parseDouble(s));
continue;
}
}
close(reader);
vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE);
for (Integer depotId : depotIds) {
VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0, capacity).build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle")
.setStartLocation(Location.Builder.newInstance().setId(depotId.toString()).setCoordinate(coords[depotId - 1]).build())
.setType(type).build();
vrpBuilder.addVehicle(vehicle);
}
for (Integer id_ : indexMap.keySet()) {
String id = id_.toString();
int index = indexMap.get(id_);
if (depotIds.isEmpty()) {
if (index == 0) {
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("traveling_salesman")
.setStartLocation(Location.Builder.newInstance().setId(id)
.setCoordinate(coords[index]).setIndex(index).build())
.build();
vrpBuilder.addVehicle(vehicle);
continue;
}
}
Service service = Service.Builder.newInstance(id)
.setLocation(Location.Builder.newInstance().setId(id)
.setCoordinate(coords[index]).setIndex(index).build())
.addSizeDimension(0, demands[index]).build();
vrpBuilder.addJob(service);
}
if (edgeType.equals("GEO")) {
List<Location> locations = new ArrayList<Location>();
for (Vehicle v : vrpBuilder.getAddedVehicles()) locations.add(v.getStartLocation());
for (Job j : vrpBuilder.getAddedJobs()) locations.add(((Service) j).getLocation());
vrpBuilder.setRoutingCost(getGEOMatrix(locations));
} else if (edgeType.equals("EXPLICIT")) {
if (edgeWeightFormat.equals("UPPER_ROW")) {
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions, true);
int fromIndex = 0;
int toIndex = 1;
for (int i = 0; i < edgeWeights.size(); i++) {
if (toIndex == dimensions) {
fromIndex++;
toIndex = fromIndex + 1;
}
matrixBuilder.addTransportDistance(fromIndex, toIndex, edgeWeights.get(i));
matrixBuilder.addTransportTime(fromIndex, toIndex, edgeWeights.get(i));
toIndex++;
}
vrpBuilder.setRoutingCost(matrixBuilder.build());
} else if (edgeWeightFormat.equals("UPPER_DIAG_ROW")) {
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions, true);
int fromIndex = 0;
int toIndex = 0;
for (int i = 0; i < edgeWeights.size(); i++) {
if (toIndex == dimensions) {
fromIndex++;
toIndex = fromIndex;
}
matrixBuilder.addTransportDistance(fromIndex, toIndex, edgeWeights.get(i));
matrixBuilder.addTransportTime(fromIndex, toIndex, edgeWeights.get(i));
toIndex++;
}
vrpBuilder.setRoutingCost(matrixBuilder.build());
} else if (edgeWeightFormat.equals("LOWER_DIAG_ROW")) {
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions, true);
int fromIndex = 0;
int toIndex = 0;
for (int i = 0; i < edgeWeights.size(); i++) {
if (toIndex > fromIndex) {
fromIndex++;
toIndex = 0;
}
matrixBuilder.addTransportDistance(fromIndex, toIndex, edgeWeights.get(i));
matrixBuilder.addTransportTime(fromIndex, toIndex, edgeWeights.get(i));
toIndex++;
}
vrpBuilder.setRoutingCost(matrixBuilder.build());
} else if (edgeWeightFormat.equals("FULL_MATRIX")) {
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions, false);
int fromIndex = 0;
int toIndex = 0;
for (int i = 0; i < edgeWeights.size(); i++) {
if (toIndex == dimensions) {
fromIndex++;
toIndex = 0;
}
matrixBuilder.addTransportDistance(fromIndex, toIndex, edgeWeights.get(i));
matrixBuilder.addTransportTime(fromIndex, toIndex, edgeWeights.get(i));
toIndex++;
}
vrpBuilder.setRoutingCost(matrixBuilder.build());
}
}
}
private VehicleRoutingTransportCosts getGEOMatrix(List<Location> noLocations) {
FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(noLocations.size(), true);
for (Location i : noLocations) {
for (Location j : noLocations) {
matrixBuilder.addTransportDistance(i.getIndex(), j.getIndex(), getDistance(i, j));
matrixBuilder.addTransportTime(i.getIndex(), j.getIndex(), getDistance(i, j));
}
}
return matrixBuilder.build();
}
private double getDistance(Location from, Location to) {
double longitude_from = getLongitude(from);
double longitude_to = getLongitude(to);
double latitude_from = getLatitude(from);
double latitude_to = getLatitude(to);
double q1 = Math.cos(longitude_from - longitude_to);
double q2 = Math.cos(latitude_from - latitude_to);
double q3 = Math.cos(latitude_from + latitude_to);
return 6378.388 * Math.acos(.5 * ((1. + q1) * q2 - (1. - q1) * q3)) + 1.;
}
private double getLatitude(Location loc) {
int deg = (int) loc.getCoordinate().getX();
double min = loc.getCoordinate().getX() - deg;
return Math.PI * (deg + 5. * min / 3.) / 180.;
}
private double getLongitude(Location loc) {
int deg = (int) loc.getCoordinate().getY();
double min = loc.getCoordinate().getY() - deg;
return Math.PI * (deg + 5. * min / 3.) / 180.;
}
private void close(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
}
private String getLine(BufferedReader reader) {
String s = null;
try {
s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
private BufferedReader getBufferedReader(String filename) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(filename)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bufferedReader;
}
}

View file

@ -0,0 +1,530 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
//package instances;
//
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.concurrent.TimeUnit;
//
//import org.apache.log4j.Level;
//import org.apache.log4j.Logger;
//import org.matsim.contrib.freight.vrp.algorithms.rr.costCalculators.JobInsertionCalculator;
//import org.matsim.contrib.freight.vrp.algorithms.rr.costCalculators.RouteAgentFactory;
//import org.matsim.contrib.freight.vrp.algorithms.rr.listener.RuinAndRecreateReport;
//import org.matsim.contrib.freight.vrp.algorithms.rr.ruin.JobDistanceAvgCosts;
//import org.matsim.contrib.freight.vrp.algorithms.rr.ruin.RuinRadial;
//import org.matsim.contrib.freight.vrp.basics.Driver;
//import org.matsim.contrib.freight.vrp.basics.Job;
//import org.matsim.contrib.freight.vrp.basics.RouteAlgorithm;
//import org.matsim.contrib.freight.vrp.basics.RouteAlgorithm.VehicleSwitchedListener;
//import org.matsim.contrib.freight.vrp.basics.Service;
//import org.matsim.contrib.freight.vrp.basics.Tour;
//import org.matsim.contrib.freight.vrp.basics.TourActivity;
//import org.matsim.contrib.freight.vrp.basics.TourStateUpdater;
//import org.matsim.contrib.freight.vrp.basics.Vehicle;
//import org.matsim.contrib.freight.vrp.basics.VehicleFleetManager;
//import org.matsim.contrib.freight.vrp.basics.VehicleFleetManagerImpl;
//import org.matsim.contrib.freight.vrp.basics.VehicleImpl;
//import org.matsim.contrib.freight.vrp.basics.VehicleImpl.Type;
//import org.matsim.contrib.freight.vrp.basics.VehicleImpl.VehicleCostParams;
//import org.matsim.contrib.freight.vrp.basics.VehicleRoute;
//import org.matsim.contrib.freight.vrp.basics.VehicleRoute.VehicleRouteCostCalculator;
//import org.matsim.contrib.freight.vrp.basics.VehicleRouteCostFunction;
//import org.matsim.contrib.freight.vrp.basics.VehicleRouteCostFunctionFactory;
//import org.matsim.contrib.freight.vrp.basics.VehicleRoutingCosts;
//import org.matsim.contrib.freight.vrp.basics.VehicleRoutingProblem;
//import org.matsim.contrib.freight.vrp.basics.VehicleRoutingProblemSolution;
//import org.matsim.contrib.freight.vrp.basics.VrpBuilder;
//import org.matsim.contrib.freight.vrp.utils.Coordinate;
//import org.matsim.contrib.freight.vrp.utils.EuclideanDistanceCalculator;
//import org.matsim.contrib.freight.vrp.utils.Locations;
//import org.matsim.contrib.freight.vrp.utils.RouteUtils;
//import org.matsim.core.utils.io.IOUtils;
//
//import ruinFactories.RadialRuinFactory;
//import selectors.SelectBest;
//import selectors.SelectRandomly;
//import strategies.GendreauPostOpt;
//import strategies.RadialAndRandomRemoveBestInsert;
//import vrp.SearchStrategy;
//import vrp.SearchStrategyManager;
//import vrp.SearchStrategyModule;
//import vrp.VehicleRoutingMetaAlgorithm;
//import acceptors.AcceptNewRemoveWorst;
//import basics.VehicleRouteFactoryImpl;
//import basics.costcalculators.AuxilliaryCostCalculator;
//import basics.costcalculators.CalculatesActivityInsertion;
//import basics.costcalculators.CalculatesServiceInsertionConsideringFixCost;
//import basics.costcalculators.CalculatesServiceInsertionOnRouteLevel;
//import basics.costcalculators.CalculatesVehTypeDepServiceInsertion;
//import basics.inisolution.CreateInitialSolution;
//import basics.insertion.ConfigureFixCostCalculator;
//import basics.insertion.DepotDistance;
//import basics.insertion.ParRegretInsertion;
//import basics.insertion.RecreationBestInsertion;
//
///**
// * test instances for the capacitated vrp with time windows. instances are from solomon
// * and can be found at:
// * http://neo.lcc.uma.es/radi-aeb/WebVRP/
// * @author stefan schroeder
// *
// */
//
//
//
//public class Taillard {
//
//
// static class MyLocations implements Locations{
//
// private Map<String,Coordinate> locations = new HashMap<String, Coordinate>();
//
// public void addLocation(String id, Coordinate coord){
// locations.put(id, coord);
// }
//
// @Override
// public Coordinate getCoord(String id) {
// return locations.get(id);
// }
// }
//
// public static final String VRPHE = "vrphe";
//
// public static final String VFM = "vfm";
//
// private static Logger logger = Logger.getLogger(Christophides.class);
//
// private String fileNameOfInstance;
//
// private String depotId;
//
// private String instanceName;
//
// private String vehicleFile;
//
// private String vehicleCostScenario;
//
// private String vrpType;
//
// private ResultWriter resultWriter;
//
// private RuinAndRecreateReport report;
//
//
// public Taillard(String fileNameOfInstance, String instanceName, String vehicleFileName, String vehicleCostScenario, String vrpType) {
// super();
// this.fileNameOfInstance = fileNameOfInstance;
// this.instanceName = instanceName;
// this.vehicleFile = vehicleFileName;
// this.vehicleCostScenario = vehicleCostScenario;
// this.vrpType = vrpType;
// }
//
// public static void main(String[] args) throws IOException {
// System.out.println("start " + System.currentTimeMillis());
// Logger.getRootLogger().setLevel(Level.INFO);
//
// int nOfProcessors = Runtime.getRuntime().availableProcessors();
// logger.info("nOfProcessors: " + nOfProcessors);
// ExecutorService executor = Executors.newFixedThreadPool(nOfProcessors+2);
//
// ResultWriter resultWriter = new ResultWriter();
//// String vrpType = "VFM";
// String vrpType = VRPHE;
// String pblm_abbr = "R101";
// String costScen = "R_19";
//
// String problem = "100_" + pblm_abbr + "_LuiShen";
// String problemFile = pblm_abbr + ".txt";
// Taillard luiShen = new Taillard("/Users/stefan/Documents/Schroeder/Dissertation/vrpInstances/cvrptw_solomon/nOfCust100/"+problemFile,
// problem, "/Users/stefan/Documents/Schroeder/Dissertation/vrpInstances/vrphe_taillard/"+costScen+".txt", costScen, vrpType);
// luiShen.setResultWriter(resultWriter);
// luiShen.run(executor);
//
// System.out.println("finish " + System.currentTimeMillis());
// resultWriter.write("output/taillard_"+ pblm_abbr + "_" + costScen + ".txt");
// resultWriter.writeSolutions("output/taillard_solution_" + pblm_abbr + "_" + costScen + ".txt");
//
// executor.shutdown();
// try {
// executor.awaitTermination(10, TimeUnit.SECONDS);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// private static String getName(int i) {
// if(i<10){
// return "0" + i;
// }
// else{
// return "" + i;
// }
// }
//
// private void setResultWriter(ResultWriter resultWriter) {
// this.resultWriter = resultWriter;
//
// }
//
// public void run(ExecutorService executor){
//
// final MyLocations myLocations = new MyLocations();
// Collection<Job> jobs = new ArrayList<Job>();
// final Map<String,Service> jobMap = readLocationsAndJobs(myLocations,jobs);
//
// VehicleRoutingCosts costs = new VehicleRoutingCosts() {
//
// @Override
// public double getBackwardTransportTime(String fromId, String toId, double arrivalTime, Driver driver, Vehicle vehicle) {
// return getTransportTime(fromId, toId, arrivalTime, null, null);
// }
//
// @Override
// public double getBackwardTransportCost(String fromId, String toId, double arrivalTime, Driver driver, Vehicle vehicle) {
// return getTransportCost(fromId, toId, arrivalTime, null, null);
// }
//
// @Override
// public double getTransportCost(String fromId, String toId, double departureTime, Driver driver, Vehicle vehicle) {
// double variableCost;
// if(vehicle == null){
// variableCost = 1.0;
// }
// else{
// variableCost = vehicle.getType().vehicleCostParams.perDistanceUnit;
// }
// return variableCost*EuclideanDistanceCalculator.calculateDistance(myLocations.getCoord(fromId), myLocations.getCoord(toId));
// }
//
// @Override
// public double getTransportTime(String fromId, String toId, double departureTime, Driver driver, Vehicle vehicle) {
// return getTransportCost(fromId, toId, departureTime, driver, vehicle);
// }
// };
//
// VrpBuilder vrpBuilder = new VrpBuilder(costs);
// for(Job j : jobs){
// vrpBuilder.addJob(j);
// }
// createVehicles(vrpBuilder);
// VehicleRoutingProblem vrp = vrpBuilder.build();
//
// VehicleRoutingMetaAlgorithm metaAlgorithm = new VehicleRoutingMetaAlgorithm(vrp);
// configure(metaAlgorithm,vrp,executor,myLocations);
// metaAlgorithm.run();
//
// printSolutions(vrp);
//
// VehicleRoutingProblemSolution bestSolution = new SelectBest().selectSolution(vrp);
//
// resultWriter.addResult(instanceName+"_"+vehicleCostScenario , instanceName, RouteUtils.getNuOfActiveRoutes(bestSolution.getRoutes()), bestSolution.getCost());
// resultWriter.addSolution(bestSolution);
//
//
// }
//
// private void printSolutions(VehicleRoutingProblem vrp) {
// for(VehicleRoutingProblemSolution s : vrp.getSolutions()){
// System.out.println("total: " + s.getCost());
// System.out.println("activeTours: " + RouteUtils.getNuOfActiveRoutes(s.getRoutes()));
// System.out.println("");
// }
//
// }
//
// private void configure(VehicleRoutingMetaAlgorithm metaAlgorithm, final VehicleRoutingProblem vrp, ExecutorService executor, MyLocations myLocations) {
// VehicleRoute.VehicleRouteCostCalculator = new VehicleRouteCostCalculator() {
//
// @Override
// public double calculate(Tour tour, Vehicle vehicle, Driver driver) {
//// return vehicle.getType().vehicleCostParams.fix + tour.getCost();
// return tour.getCost();
// }
//
// };
//
//// final VehicleFleetManager vehicleFleetManager = new InfiniteVehicles(vrp.getVehicles());
// final VehicleFleetManager vehicleFleetManager = new VehicleFleetManagerImpl(vrp.getVehicles());
//
// final VehicleRouteCostFunctionFactory costFuncFac = getFac();
//
// AuxilliaryCostCalculator auxilliaryCostCalculator = new AuxilliaryCostCalculator(vrp.getCosts(), costFuncFac);
// CalculatesActivityInsertion actInsertion = new CalculatesActivityInsertion(auxilliaryCostCalculator,0,5);
//// CalculatesServiceInsertion standardServiceInsertion = new CalculatesServiceInsertion(actInsertion);
// CalculatesServiceInsertionOnRouteLevel standardServiceInsertion = new CalculatesServiceInsertionOnRouteLevel(actInsertion,vrp.getCosts(),costFuncFac);
// CalculatesServiceInsertionOnRouteLevel.MEMORYSIZE_FORPROMISING_INSERTIONPOSITIONS = 2;
// CalculatesServiceInsertionConsideringFixCost withFixCost = new CalculatesServiceInsertionConsideringFixCost(standardServiceInsertion);
// withFixCost.setWeightOfFixCost(0.0);
//
// final JobInsertionCalculator vehicleTypeDepInsertionCost = new CalculatesVehTypeDepServiceInsertion(vehicleFleetManager, standardServiceInsertion);
//
// final TourStateUpdater tourStateCalculator = new TourStateUpdater(vrp.getCosts(),costFuncFac);
// tourStateCalculator.setTimeWindowUpdate(false);
//
// RouteAgentFactory routeAgentFactory = new RouteAgentFactory(){
//
// @Override
// public RouteAlgorithm createAgent(VehicleRoute route) {
// VehicleSwitchedListener switched = new VehicleSwitchedListener() {
//
// @Override
// public void vehicleSwitched(Vehicle oldVehicle, Vehicle newVehicle) {
// vehicleFleetManager.unlock(oldVehicle);
// vehicleFleetManager.lock(newVehicle);
// }
//
// };
// RouteAlgorithmImpl agent = new RouteAlgorithmImpl(vehicleTypeDepInsertionCost, tourStateCalculator);
// agent.getListeners().add(switched);
// return agent;
// }
//
// };
//
// ParRegretInsertion regretInsertion = new ParRegretInsertion(executor, routeAgentFactory);
// regretInsertion.getListener().add(new ConfigureFixCostCalculator(vrp, withFixCost));
// regretInsertion.setJobDistance(new DepotDistance(myLocations, depotId));
// regretInsertion.scoreParam_of_timeWindowLegth = 0.5;
// regretInsertion.scoreParam_of_distance = 0.2;
// regretInsertion.setVehicleRouteFactory(new VehicleRouteFactoryImpl(depotId));
//
//
// RecreationBestInsertion bestInsertion = new RecreationBestInsertion(routeAgentFactory);
// bestInsertion.getListener().add(new ConfigureFixCostCalculator(vrp, withFixCost));
// bestInsertion.setVehicleRouteFactory(new VehicleRouteFactoryImpl(depotId));
//
//// for(int i=0;i<3;i++){
// VehicleRoutingProblemSolution vrpSol = new CreateInitialSolution(bestInsertion).createInitialSolution(vrp);
// vrp.getSolutions().add(vrpSol);
//// }
//
//
// RadialAndRandomRemoveBestInsert smallNeighborHoodSearchModule = new RadialAndRandomRemoveBestInsert(vrp, vehicleFleetManager, routeAlgorithm);
// smallNeighborHoodSearchModule.setCalcConsideringFix(withFixCost);
// smallNeighborHoodSearchModule.setStateCalc(tourStateCalculator);
// smallNeighborHoodSearchModule.setInsertionStrategy(bestInsertion);
// smallNeighborHoodSearchModule.setAuxilliaryCostCalculator(auxilliaryCostCalculator);
//
// SearchStrategy smallNeighborHoodSearch = new SearchStrategy(new SelectRandomly(), new AcceptNewRemoveWorst());
//
// smallNeighborHoodSearch.addModule(smallNeighborHoodSearchModule);
//
// GendreauPostOpt postOpt = new GendreauPostOpt(vrp, routeAgentFactory,
// (RuinRadial) new RadialRuinFactory(0.2, new JobDistanceAvgCosts(vrp.getCosts()), routeAgentFactory).createStrategy(vrp),
// bestInsertion);
// postOpt.setFleetManager(vehicleFleetManager);
// postOpt.setVehicleRouteFactory(new VehicleRouteFactoryImpl(depotId));
// postOpt.setMaxIterations(2000);
// postOpt.setShareOfJobsToRuin(0.18);
//// smallNeighborHoodSearch.addModule(postOpt);
//
//
//// SearchStrategy strat2 = new SearchStrategy(new SelectBest(), new AcceptNewRemoveWorst());
//// GendreauPostOpt postOpt2 = new GendreauPostOpt(vrp, routeAgentFactory,
//// (RuinRadial) new RadialRuinFactory(0.2, new JobDistanceAvgCosts(vrp.getCosts()), routeAgentFactory).createStrategy(vrp),
//// bestInsertion);
//// postOpt2.setFleetManager(vehicleFleetManager);
//// postOpt2.setVehicleRouteFactory(new VehicleRouteFactoryImpl(depotId));
//// postOpt2.setMaxIterations(2000);
//// postOpt2.setShareOfJobsToRuin(0.1);
//// strat2.addModule(postOpt2);
//
// SearchStrategyModule solutionVerifier = new SearchStrategyModule() {
//
// @Override
// public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
// logger.info("verify solution");
// if(SolutionVerifier.resultOfSolutionEqualsSumOfIndividualRouteCost(vrpSolution, vrp, costFuncFac,false)) return vrpSolution;
// throw new IllegalStateException("solution is not valid");
// }
// };
// smallNeighborHoodSearch.addModule(solutionVerifier);
//
// SearchStrategyManager strategyManager = new SearchStrategyManager();
// strategyManager.addStrategy(smallNeighborHoodSearch, 1.0);
//// strategyManager.addStrategy(strat2, 0.3);
//
// metaAlgorithm.setSearchStrategyManager(strategyManager);
// metaAlgorithm.setMaxIterations(20);
// VehicleRoutingProblem.SOLUTION_MEMORY = 4;
//
//
// }
//
// private VehicleRouteCostFunctionFactory getFac() {
// VehicleRouteCostFunctionFactory fac = new VehicleRouteCostFunctionFactory() {
//
// @Override
// public VehicleRouteCostFunction createCostFunction(Vehicle vehicle, Driver driver) {
// return new VehicleRouteCostFunction(){
//
// double cost = 0.0;
//
// @Override
// public void handleActivity(TourActivity tourAct, double startTime, double endTime) {
// if(startTime > tourAct.getLatestOperationStartTime()){
// cost += Double.MAX_VALUE;
// }
// }
//
// @Override
// public void handleLeg(TourActivity fromAct, TourActivity toAct, double depTime, double tpCost) {
// cost += tpCost;
//
// }
//
// @Override
// public double getCost() {
// return cost;
// }
//
// @Override
// public void finish() {
//
//
// }
//
// @Override
// public void reset() {
//
// }
//
// };
// }
// };
// return fac;
// }
//
// private void createVehicles(VrpBuilder vrpBuilder) {
// BufferedReader reader = IOUtils.getBufferedReader(vehicleFile);
// String line = null;
// int vehicleIdColumn = 0;
// int capacityColumn = 1;
// int fixColumn = 2;
// int varColumn = 3;
// int nOfVehiclesColumn = 4;
// boolean firstLine = true;
// try {
// while((line = reader.readLine()) != null){
// if(firstLine){
// firstLine = false;
// continue;
// }
// String[] tokens = line.split(";");
// String vehicleId = tokens[vehicleIdColumn];
// int capacity = Integer.parseInt(tokens[capacityColumn]);
// int fixCost = Integer.parseInt(tokens[fixColumn]);
// double var;
// if(vrpType.equals(VRPHE)){
// var = Double.parseDouble(tokens[varColumn]);
// }
// else {
// var = 1.0;
// }
// int nOfVehicles = Integer.parseInt(tokens[nOfVehiclesColumn]);
// for(int i=0;i<nOfVehicles;i++){
// String vId = vehicleId + "_" + (i+1);
// VehicleCostParams costparams = VehicleImpl.getFactory().createVehicleCostParams(fixCost, 0.0, var);
// Type type = VehicleImpl.getFactory().createType(vehicleId, capacity, costparams);
// VehicleImpl v = VehicleImpl.getFactory().createVehicle(vId, depotId, type);
// vrpBuilder.addVehicle(v);
// }
// }
// reader.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// private Map<String,Service> readLocationsAndJobs(MyLocations locations, Collection<Job> jobs){
// BufferedReader reader = IOUtils.getBufferedReader(fileNameOfInstance);
// String line = null;
// int counter = 0;
// Map<String,Service> jobMap = new HashMap<String, Service>();
// try {
// while((line = reader.readLine()) != null){
// line = line.replace("\r", "");
// line = line.trim();
// String[] tokens = line.split(" +");
// counter++;
// if(counter == 5){
// int vehicleCap = Integer.parseInt(tokens[1]);
// continue;
// }
//
// if(counter > 9){
// Coordinate coord = makeCoord(tokens[1],tokens[2]);
// double depotStart = 0.0;
// double depotEnd = Double.MAX_VALUE;
// String customerId = tokens[0];
// locations.addLocation(customerId, coord);
// int demand = Integer.parseInt(tokens[3]);
// double start = Double.parseDouble(tokens[4]);
// double end = Double.parseDouble(tokens[5]);
// double serviceTime = Double.parseDouble(tokens[6]);
// if(counter == 10){
// depotStart = start;
// depotEnd = end;
// depotId = tokens[0];
//
// }
// else{
// Service service = VrpUtils.createService("" + counter, customerId, demand, 0.0, 0.0, Double.MAX_VALUE);
//// Shipment shipment = VrpUtils.createShipment("" + counter, depotId, customerId, demand,
//// VrpUtils.createTimeWindow(depotStart, depotEnd), VrpUtils.createTimeWindow(start, end));
//// shipment.setDeliveryServiceTime(serviceTime);
// jobs.add(service);
// jobMap.put(customerId, service);
//// jobs.add(shipment);
//// j
//// Shipment shipment = VrpUtils.createShipment("" + counter, depotId, customerId, demand,
//// VrpUtils.createTimeWindow(depotStart, depotEnd), VrpUtils.createTimeWindow(start, end));
//// shipment.setDeliveryServiceTime(serviceTime);
//// jobs.add(shipment);
// }
// }
// }
// reader.close();
// } catch (NumberFormatException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return jobMap;
// }
//
// private Coordinate makeCoord(String xString, String yString) {
// double x = Double.parseDouble(xString);
// double y = Double.parseDouble(yString);
// return new Coordinate(x,y);
// }
//
//}

View file

@ -0,0 +1,173 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.reader;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.FleetSize;
import com.graphhopper.jsprit.core.problem.io.VrpXMLWriter;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import java.io.*;
/**
* Reads modified files from Taillard's website
* http://mistic.heig-vd.ch/taillard/problemes.dir/vrp.dir/vrp.html. You can find the modified version here:
* jsprit-instances/instances/vrph.
* <p/>
* <p>See {@link VrphType} what kind of problems can be generated
*
* @author schroeder
*/
public class VrphGoldenReader {
/**
* <b>FSMD</b> - Fleet Size and Mix with Dependent costs
* <p><b>FSMF</b> - Fleet Size and Mix with Fixed costs
* <p><b>FSMFD</b> - Fleet Size and Mix with Fixed and Dependent costs
* <p><b>HVRPD</b> - Heterogeneous Vehicle Routing Problem with Dependent costs and finite (limited) fleet
* <p><b>HVRPFD</b> - Heterogeneous Vehicle Routing Problem with Fixed and Dependent costs and finite (limited) fleet
*
* @author schroeder
*/
public enum VrphType {
FSMD,
HVRPD,
FSMF,
FSMFD,
HVRPFD
}
private final VehicleRoutingProblem.Builder vrpBuilder;
private final VrphType vrphType;
public VrphGoldenReader(Builder vrpBuilder, VrphType vrphType) {
super();
this.vrpBuilder = vrpBuilder;
this.vrphType = vrphType;
}
public void read(String filename) {
BufferedReader reader = getReader(filename);
String line;
boolean firstline = true;
Coordinate depotCoord = null;
int customerCount = 0;
Integer nuOfCustomer = 0;
while ((line = readLine(reader)) != null) {
String trimedLine = line.trim();
if (trimedLine.startsWith("//")) continue;
String[] tokens = trimedLine.split("\\s+");
if (firstline) {
nuOfCustomer = Integer.parseInt(tokens[0]);
customerCount = 0;
firstline = false;
} else if (customerCount <= nuOfCustomer) {
if (customerCount == 0) {
depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]));
} else {
Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0]).addSizeDimension(0, Integer.parseInt(tokens[3]));
serviceBuilder.setLocation(Location.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])));
vrpBuilder.addJob(serviceBuilder.build());
}
customerCount++;
} else if (trimedLine.startsWith("v")) {
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_" + tokens[1]).addCapacityDimension(0, Integer.parseInt(tokens[2]));
int nuOfVehicles = 1;
if (vrphType.equals(VrphType.FSMF)) {
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
} else if (vrphType.equals(VrphType.FSMFD)) {
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
if (tokens.length > 4) {
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
} else
throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
} else if (vrphType.equals(VrphType.FSMD)) {
if (tokens.length > 4) {
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
} else
throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
} else if (vrphType.equals(VrphType.HVRPD)) {
if (tokens.length > 4) {
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
nuOfVehicles = Integer.parseInt(tokens[5]);
vrpBuilder.setFleetSize(FleetSize.FINITE);
} else
throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
} else if (vrphType.equals(VrphType.HVRPFD)) {
if (tokens.length > 4) {
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
nuOfVehicles = Integer.parseInt(tokens[5]);
vrpBuilder.setFleetSize(FleetSize.FINITE);
} else
throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
for (int i = 0; i < nuOfVehicles; i++) {
VehicleTypeImpl type = typeBuilder.build();
VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle_" + tokens[1] + "_" + i)
.setStartLocation(Location.newInstance(depotCoord.getX(), depotCoord.getY())).setType(type).build();
vrpBuilder.addVehicle(vehicle);
}
}
}
closeReader(reader);
}
private void closeReader(BufferedReader reader) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readLine(BufferedReader reader) {
String readLine = null;
try {
readLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return readLine;
}
private BufferedReader getReader(String filename) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(filename)));
return bufferedReader;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
VrphGoldenReader goldenReader = new VrphGoldenReader(vrpBuilder, VrphType.FSMD);
goldenReader.read("instances/vrph/orig/cn_13mix.txt");
VehicleRoutingProblem vrp = vrpBuilder.build();
new VrpXMLWriter(vrp).write("instances/vrph/cn_13mix_VRPH_INFINITE.xml");
}
}

View file

@ -0,0 +1,249 @@
/*******************************************************************************
* 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 com.graphhopper.jsprit.instance.util;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.util.BenchmarkInstance;
import com.graphhopper.jsprit.instance.reader.ChristofidesReader;
import com.graphhopper.jsprit.instance.reader.CordeauReader;
import com.graphhopper.jsprit.instance.reader.SolomonReader;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class Instances {
/**
* Returns a collection of {@link BenchmarkInstance} which are Cordeau's p instances.
* <p>Note that this assumes that within the folder 'inputFolder' 23 p-instances are located with their original name, i.e. p01,p02,...,p23.
* <p>It also assumes that solution files are also located in inputFolder ending with .res
*
* @param inputFolder where cordeau's p instances are located. It must end without '/' such as instances/cordeau.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllCordeauP(String inputFolder) {
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 23; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/p" + getInstanceNu(i + 1);
new CordeauReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("p" + getInstanceNu(i + 1), p, getBestKnown(file), null));
}
return instances;
}
private static double getBestKnown(String file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(file + ".res")));
String first = reader.readLine();
Double result = Double.valueOf(first);
reader.close();
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
private static String getInstanceNu(int i) {
if (i < 10) return "0" + i;
return "" + i;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Cordeau's pr instances.
* <p>Note that this assumes that within the folder 'inputFolder' 10 p-instances are located with their original name, i.e. pr01,pr02,...,pr10.
* <p>It also assumes that solution files are also located in inputFolder ending with .res
*
* @param inputFolder
* @param inputFolder where cordeau's pr instances are located. It must end without '/' such as instances/cordeau.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllCordeauPR(String inputFolder) {
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 10; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/pr" + getInstanceNu(i + 1);
new CordeauReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("pr" + getInstanceNu(i + 1), p, getBestKnown(file), null));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Christofides vrpnc instances.
* <p>Note that this assumes that within the folder 'inputFolder' 14 vrpnc-instances are located with their original name, i.e. vrpnc1,vrpnc2,...,vrpnc14.
*
* @param inputFolder where christofides vrpnc instances are located. It must end without '/' such as instances/christofides.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllChristofides(String inputFolder) {
List<Double> bestKnown = Arrays.asList(524.61, 835.26, 826.14, 1028.42, 1291.29, 555.43, 909.68, 865.49, 1162.55, 1395.85, 1042.11, 819.56, 1541.14, 866.37);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 14; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/vrpnc" + (i + 1) + ".txt";
new ChristofidesReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("vrpnc" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), null));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Solomon instances.
* <p>Note that this assumes that within the folder 'inputFolder' 9 C1-instances are located with their original name, i.e. C101.txt,C102.txt,...,C109.txt.
* <p>Note that unlike the original problems, a fixed-cost value of 1000 is set for each employed vehicle.
*
* @param inputFolder where solomon C1 instances are located. It must end without '/' such as instances/solomon.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllSolomonC1(String inputFolder) {
List<Double> bestKnown = Arrays.asList(828.94, 828.94, 828.06, 824.78, 828.94, 828.94, 828.94, 828.94, 828.94);
List<Double> bestKnowVehicles = Arrays.asList(10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 9; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/C1" + getInstanceNu(i + 1) + ".txt";
new SolomonReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("C1" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), bestKnowVehicles.get(i).doubleValue()));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Solomon instances.
* <p>Note that this assumes that within the folder 'inputFolder' 8 C2-instances are located with their original name, i.e. C201.txt,C202.txt,...,C208.txt.
* <p>Note that unlike the original problems, a fixed-cost value of 1000 is set for each employed vehicle.
*
* @param inputFolder where solomon C2 instances are located. It must end without '/' such as instances/solomon.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllSolomonC2(String inputFolder) {
List<Double> bestKnown = Arrays.asList(591.56, 591.56, 591.17, 590.60, 588.88, 588.49, 588.29, 588.32);
List<Double> bestKnowVehicles = Arrays.asList(3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 8; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/C2" + getInstanceNu(i + 1) + ".txt";
new SolomonReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("C2" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), bestKnowVehicles.get(i).doubleValue()));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Solomon instances.
* <p>Note that this assumes that within the folder 'inputFolder' 12 R1-instances are located with their original name, i.e. R101.txt,R102.txt,...,R112.txt.
* <p>Note that unlike the original problems, a fixed-cost value of 1000 is set for each employed vehicle.
*
* @param inputFolder where solomon R1 instances are located. It must end without '/' such as instances/solomon.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllSolomonR1(String inputFolder) {
List<Double> bestKnown = Arrays.asList(1650.80, 1486.12, 1292.68, 1007.31, 1377.11, 1252.03, 1104.66, 960.88, 1194.73, 1118.84, 1096.72, 982.14);
List<Double> bestKnowVehicles = Arrays.asList(19.0, 17.0, 13.0, 9.0, 14.0, 12.0, 10.0, 9.0, 11.0, 10.0, 10.0, 9.0);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 12; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/R1" + getInstanceNu(i + 1) + ".txt";
new SolomonReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("R1" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), bestKnowVehicles.get(i).doubleValue()));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Solomon instances.
* <p>Note that this assumes that within the folder 'inputFolder' 11 R1-instances are located with their original name, i.e. R201.txt,R202.txt,...,R111.txt.
* <p>Note that unlike the original problems, a fixed-cost value of 1000 is set for each employed vehicle.
*
* @param inputFolder
* @param inputFolder where solomon R2 instances are located. It must end without '/' such as instances/solomon.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllSolomonR2(String inputFolder) {
List<Double> bestKnown = Arrays.asList(1252.37, 1191.70, 939.50, 825.52, 994.42, 906.14, 890.61, 726.82, 909.16, 939.37, 885.71);
List<Double> bestKnowVehicles = Arrays.asList(4.0, 3.0, 3.0, 2.0, 3.0, 3.0, 2.0, 2.0, 3.0, 3.0, 2.0);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 11; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/R2" + getInstanceNu(i + 1) + ".txt";
new SolomonReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("R2" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), bestKnowVehicles.get(i).doubleValue()));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Solomon instances.
* <p>Note that this assumes that within the folder 'inputFolder' 8 RC1-instances are located with their original name, i.e. RC101.txt,RC102.txt,...,RC108.txt.
* <p>Note that unlike the original problems, a fixed-cost value of 1000 is set for each employed vehicle.
*
* @param inputFolder where solomon RC1 instances are located. It must end without '/' such as instances/solomon.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllSolomonRC1(String inputFolder) {
List<Double> bestKnown = Arrays.asList(1696.94, 1554.75, 1261.67, 1135.48, 1629.44, 1424.73, 1230.48, 1139.82);
List<Double> bestKnowVehicles = Arrays.asList(14.0, 12.0, 11.0, 10.0, 13.0, 11.0, 11.0, 10.0);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 8; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/RC1" + getInstanceNu(i + 1) + ".txt";
new SolomonReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("RC1" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), bestKnowVehicles.get(i).doubleValue()));
}
return instances;
}
/**
* Returns a collection of {@link BenchmarkInstance} which are Solomon instances.
* <p>Note that this assumes that within the folder 'inputFolder' 8 RC2-instances are located with their original name, i.e. RC201.txt,RC202.txt,...,RC208.txt.
* <p>Note that unlike the original problems, a fixed-cost value of 1000 is set for each employed vehicle.
*
* @param inputFolder
* @param inputFolder where solomon RC2 instances are located. It must end without '/' such as instances/solomon.
* @return a collection of {@link BenchmarkInstance}
*/
public static Collection<BenchmarkInstance> getAllSolomonRC2(String inputFolder) {
List<Double> bestKnown = Arrays.asList(1406.94, 1365.65, 1049.62, 798.46, 1297.65, 1146.32, 1061.14, 828.14);
List<Double> bestKnowVehicles = Arrays.asList(4.0, 3.0, 3.0, 3.0, 4.0, 3.0, 3.0, 3.0);
Collection<BenchmarkInstance> instances = new ArrayList<BenchmarkInstance>();
for (int i = 0; i < 8; i++) {
VehicleRoutingProblem.Builder builder = VehicleRoutingProblem.Builder.newInstance();
String file = inputFolder + "/RC2" + getInstanceNu(i + 1) + ".txt";
new SolomonReader(builder).read(file);
VehicleRoutingProblem p = builder.build();
instances.add(new BenchmarkInstance("RC2" + getInstanceNu(i + 1), p, bestKnown.get(i).doubleValue(), bestKnowVehicles.get(i).doubleValue()));
}
return instances;
}
}