diff --git a/VRP_Solvers/src/VRP/SolutionSet.java b/VRP_Solvers/src/VRP/SolutionSet.java index c80acb8..760fe24 100644 --- a/VRP_Solvers/src/VRP/SolutionSet.java +++ b/VRP_Solvers/src/VRP/SolutionSet.java @@ -8,6 +8,8 @@ public abstract class SolutionSet { //DERIVAR ESTA CLASE CON LOS ATRIBUTOS PARTICULARES QUE RESULTEN //INTERESANTES PARA CADA ALGORITMO, Y SUS GETTERS Y SETTERS. + // ПОЛУЧИТЬ ЭТОТ КЛАСС С КОНКРЕТНЫМИ АТРИБУТАМИ, КОТОРЫЕ ВОЗНИКАЮТ + // ИНТЕРЕСНЫЕ ДЛЯ КАЖДОГО АЛГОРИТМА, А ТАКЖЕ ИХ ГЕТТЕРЫ И СЕТТЕРЫ. protected double executionTime; protected SolutionSet(double executionTime) { diff --git a/VRP_Solvers/src/VRP/VehicleRoutingProblem.java b/VRP_Solvers/src/VRP/VehicleRoutingProblem.java index 2d290b4..a67e14a 100644 --- a/VRP_Solvers/src/VRP/VehicleRoutingProblem.java +++ b/VRP_Solvers/src/VRP/VehicleRoutingProblem.java @@ -24,6 +24,16 @@ public class VehicleRoutingProblem { * @param dropTime Restriccion: tiempo que tarda cada vehiculo en descargar * sus productos en la ubicacion que corresponde a cada cliente (igual para * todos los clientes) + * Конструктор, который инициализирует все параметры, которые полностью определяют + * * конкретный экземпляр VRP. + * * + * * @param numberOfCustomers Количество клиентов экземпляра + * * @ param vehicleCapacity емкость а / м (идент. для всех) + * * @ param maximumRouteTime Restriccion: максимальное время, которое автомобиль может + * * использование для обслуживания маршрута + * * @ param dropTime Restriccion: время, необходимое для загрузки каждого автомобиля + * * ваши продукты в месте, которое соответствует каждому клиенту (равному для + * * все клиенты) */ public VehicleRoutingProblem(int numberOfCustomers, int vehicleCapacity, int maximumRouteTime, int dropTime) { @@ -36,12 +46,16 @@ public VehicleRoutingProblem(int numberOfCustomers, int vehicleCapacity, // El customer 0 es en realidad el deposito de camiones, que no tiene // demanda alguna de ningun producto. + //Customer 0 на самом деле депо, которое не имеет + //спроса на любой из продуктов this.customerDemands[0] = 0; this.costs = new double[numberOfCustomers + 1][numberOfCustomers + 1]; //Se inicializa en costo "infinito" el arreglo de costos, para simular //el hecho de que algunas rutas son invalidas. + //Инициализируется в "бесконечной" стоимости урегулирования затрат, чтобы имитировать + //тот факт, что некоторые маршруты недействительны. initializeCostsArray(); } diff --git a/VRP_Solvers/src/VRP_ANT/Ant.java b/VRP_Solvers/src/VRP_ANT/Ant.java index 57f76ce..988742b 100644 --- a/VRP_Solvers/src/VRP_ANT/Ant.java +++ b/VRP_Solvers/src/VRP_ANT/Ant.java @@ -5,7 +5,7 @@ /** * La clase Ant representa a una hormiga individual. - * + * Класс Ant представляет отдельного муравья. * @author Marlin Aranguren * @author Simon Rojas */ @@ -13,18 +13,22 @@ public class Ant implements Comparable { private final int numberOfCustomers; //Variable compartida + // Общие переменные private double[][] pheromones; private double totalDistance; private double totalRouteTime; private double dropTime; //INICIO DE PARAMETROS DE AJUSTE + //НАЧАЛО НАСТРОЙКИ ПАРАМЕТРОВ private int alfa; private int beta; private double f; private double g; //FIN DE PARAMETROS DE AJUSTE + //КОНЕЦ НАСТРОЙКИ ПАРАМЕТРОВ private ArrayList> solution; //No incluye el depot + //Не включает depot private ArrayList notVisited; private ArrayList feasibleCustomers; private ArrayList usedArcs; @@ -42,6 +46,7 @@ public Ant(double[][] pheromones, VehicleRoutingProblem vrpInstance, dropTime = vrpInstance.getDropTime(); this.pheromones = pheromones; //CUIDADO: Solo sirve en Java 7 (ya que se usa 'diamond inference')! + //Осторожно: он работает только в Java 7 (поскольку используется "diamond inference")! solution = new ArrayList<>(numberOfCustomers + 1); notVisited = new ArrayList<>(numberOfCustomers + 1); @@ -56,9 +61,11 @@ public Ant(double[][] pheromones, VehicleRoutingProblem vrpInstance, /** * Prepara a esta hormiga para iniciar una nueva exploracion - * + * Подготовьте этого муравья, чтобы начать новое исследование * @param initialCustomer nuevo cliente inicial desde donde se iniciara la * busqueda + * новый начальный клиент с момента запуска поиска + * */ public void reset() { totalRouteTime = 0; @@ -121,7 +128,8 @@ private int nextCustomer(int currentCustomer, double currentRouteTime, } } } - throw new Exception("No se encontró un nuevo cliente al que viajar"); + throw new Exception("Не найден новый клиент для путешествий"); + //No se encontró un nuevo cliente al que viajar } private double getVisibility(int customer0, int customer1) { @@ -232,8 +240,9 @@ public ArrayList> getSolution() { @Override public String toString() { - return "Distancia: " + totalDistance; + return "Дистанция: " + totalDistance; } + //Distancia: private static class Arc { @@ -265,6 +274,8 @@ private void localSearch() { private void generateNeighbor() { //Se generará un vecino a traves del metodo 2-Opt y si es mejor, //quedara como nueva solucion. + //Сосед будет сгенерирован через метод 2-Opt, и если лучше, + // останется новым решением. int numberOfRoutes = solution.size(); int routeIndex = Math.round((float) Math.random() * (numberOfRoutes - 1)); @@ -273,6 +284,7 @@ private void generateNeighbor() { if (routeSize >= 3) { //Hacer 2-Opt + //Сделать 2-Opt int index0 = Math.round((float) Math.random() * (routeSize - 1)); int delta = Math.round((float) Math.random() * (routeSize - 2)) + 1; diff --git a/VRP_Solvers/src/VRP_ILS/IteratedLocalSearchAlgorithm.java b/VRP_Solvers/src/VRP_ILS/IteratedLocalSearchAlgorithm.java index 288916e..586d961 100644 --- a/VRP_Solvers/src/VRP_ILS/IteratedLocalSearchAlgorithm.java +++ b/VRP_Solvers/src/VRP_ILS/IteratedLocalSearchAlgorithm.java @@ -13,6 +13,7 @@ public class IteratedLocalSearchAlgorithm implements MetaheuristicOptimizationAlgorithm { //INICIO de estructuras para representar una solucion al problema + // Начало структур для представления решения проблемы Integer[] customers; List> currentRoutes; List costOfRoutes; @@ -24,9 +25,12 @@ public class IteratedLocalSearchAlgorithm double bestTotalDistance; //FIN de estructuras para representar una solución al problema //INICIO de parametros configurables por el usuario + //Конец структур для представления решения проблемы + // Начало настраиваемых пользователем параметров int maxIter = 10000; int localSearchMaxIter = 100000; //FIN de parametros configurables por el usuario + // Конец настраиваемых пользователем параметров VehicleRoutingProblem vrpInstance; int numberOfCustomers; private static final double mili = 1000000000.0; @@ -61,7 +65,8 @@ public IteratedLocalSearchAlgorithm(VehicleRoutingProblem vrpInstance) { this.totalCost = this.vrpInstance.getDropTime() * numberOfCustomers; this.totalDistance = 0; constructInitialSolution(); - System.out.println("Distancia inicial: " + bestTotalDistance); + System.out.println("Начальное расстояние: " + bestTotalDistance); + // Distancia inicial: } private void constructInitialSolution() { @@ -250,10 +255,12 @@ private void printResult() { int i = 0; for (List route : bestRoutes) { System.out.println("0" + route.toString() + "0"); - System.out.println("Costo ruta: " + costOfRoutes.get(i)); + System.out.println("Стоимость маршрута: " + costOfRoutes.get(i)); + // Costo ruta i++; } - System.out.println("Costo total: " + this.totalDistance); + System.out.println("Общая стоимость: " + this.totalDistance); + // Costo total } private boolean validateResult() { @@ -262,7 +269,8 @@ private boolean validateResult() { n += route.size(); } if (n != numberOfCustomers) { - System.out.println("Invalida por numero de customers"); + System.out.println("неправильное количество клиентов"); + // Invalida por numero de customers return false; } @@ -281,7 +289,8 @@ private boolean validateResult() { costoRuta += vrpInstance.getCost(route.get(route.size() - 1), 0); if (demandaRuta > vrpInstance.getVehicleCapacity() || costoRuta >= vrpInstance.getMaximumRouteTime()) { - System.out.println("Invalida por demanda o por maximum route time"); + System.out.println("Неправильный спрос или максимальное время маршрута"); + //Invalida por demanda o por maximum route time return false; } i++; @@ -300,7 +309,8 @@ private boolean validateResult() { for (int j = 0; j < numberOfCustomers; j++) { if (ocurrences[j] != 1) { - System.out.println("Invalida por repeticion de customer"); + System.out.println("Неправильное повторение клиента"); + // Invalida por repeticion de customer return false; } } @@ -330,6 +340,8 @@ private void localSearch() { private void generateNeighbor() { //Se generará un vecino a traves del metodo 2-Opt y si es mejor, //quedara como nueva solucion. + // Сосед будет сгенерирован через метод 2-Opt, и если лучше, + // останется новым решением. int numberOfRoutes = currentRoutes.size(); int routeIndex = Math.round((float) Math.random() * (numberOfRoutes - 1)); @@ -338,6 +350,7 @@ private void generateNeighbor() { if (routeSize >= 3) { //Hacer 2-Opt + // Делаем 2-Opt int index0 = Math.round((float) Math.random() * (routeSize - 1)); int delta = Math.round((float) Math.random() * (routeSize - 2)) + 1; diff --git a/VRP_Solvers/src/VRP_ILS/Main.java b/VRP_Solvers/src/VRP_ILS/Main.java index 4da53a9..d704903 100644 --- a/VRP_Solvers/src/VRP_ILS/Main.java +++ b/VRP_Solvers/src/VRP_ILS/Main.java @@ -2,6 +2,7 @@ import VRP.VehicleRoutingProblem; import java.io.*; +import java.util.Arrays; /** * @author Andrea Aranguren @@ -49,28 +50,96 @@ private static void LoadData(String path) throws Exception { } fillMatrix(coord); } + private static String[] Split_line(String line) + { + String separator[]; + separator = line.split(" "); + int i = 0; + if (separator[i].equals("")) { + i++; + } + return Arrays.copyOfRange(separator, i, separator.length); + } + // adaptation for TSPLib95 + private static void LoadData_new(String path) throws Exception { + BufferedReader file = new BufferedReader(new FileReader(path)); + String separator[]; + file.readLine(); + file.readLine(); + file.readLine(); + String line = file.readLine(); + separator = line.split(" "); + int n = Integer.parseInt(separator[2]); + file.readLine(); + line = file.readLine(); + separator = line.split(" "); + int capacity = Integer.parseInt(separator[2]); + int maxRouteTime = 999999; + int dropTime = 0; + vrp = new VehicleRoutingProblem(n-1, capacity, maxRouteTime, dropTime); + file.readLine(); + double coord[][] = new double[vrp.getNumberOfCustomers() + 1][2]; + line = file.readLine(); +// separator = line.split(" "); +// int i = 0; +// if (separator[i].equals("")) { +// i++; +// } + separator = Split_line(line); + coord[0][0] = Integer.parseInt(separator[1]); + coord[0][1] = Integer.parseInt(separator[2]); + //vrp.addCustomerDemand(0, 0); + for (int j = 1; j <= vrp.getNumberOfCustomers(); j++) { + line = file.readLine(); +// separator = line.split(" "); +// int i = 0; +// if (separator[i].equals("")) { +// i++; +// } + separator = Split_line(line); + coord[j][0] = Integer.parseInt(separator[1]); + coord[j][1] = Integer.parseInt(separator[2]); + // vrp.addCustomerDemand(j, Integer.parseInt(separator[i + 2])); + } + fillMatrix(coord); + file.readLine(); + for (int j = 0; j <= vrp.getNumberOfCustomers(); j++) { + line = file.readLine(); + separator = Split_line(line); + vrp.addCustomerDemand(j, Integer.parseInt(separator[1])); + } + } private static void writeFile(ILSSolutionSet solution, String instanceName) throws IOException { - String outFileName = ("stat.").concat(instanceName); + //String outFileName = ("stat.").concat(instanceName); + String outFileName = instanceName.concat("out.txt"); BufferedWriter out = new BufferedWriter(new FileWriter(outFileName)); - out.write("Distancia de la mejor solucion (CON DROP TIME): " + solution.getTotaldistance()); + out.write("Лучшее решение расстояние (с DROP TIME): " + solution.getTotaldistance()); + // Distancia de la mejor solucion (CON DROP TIME): out.newLine(); - out.write("Costo de la mejor solucion (SIN DROP TIME): " + solution.getBestDistance()); + out.write("Стоимость наилучшего решения (без DROP TIME): " + solution.getBestDistance()); + // Costo de la mejor solucion (SIN DROP TIME): out.newLine(); - out.write("Iteracion de la mejor solucion: " + solution.getBestIteration()); + out.write("Итерация лучшего решения: " + solution.getBestIteration()); + //Iteracion de la mejor solucion: out.newLine(); - out.write("Iteraciones hechas por el programa: " + solution.getNumberOfIterations()); + out.write("Итерации, сделанные программой: " + solution.getNumberOfIterations()); + // Iteraciones hechas por el programa: out.newLine(); - out.write("Tiempo en el que se encontro la mejor solucion (s): " + out.write("Время, когда было найдено лучшее решение (s): " + solution.getBestTime()); + // Tiempo en el que se encontro la mejor solucion (s): out.newLine(); - out.write("Tiempo total de la corrida del algoritmo (s): " + solution.getExecutionTime()); + out.write("Общее время работы алгоритма (s): " + solution.getExecutionTime()); + //Tiempo total de la corrida del algoritmo out.newLine(); - out.write("Numero de rutas de la solucion: " + solution.getNumberOfRoutes()); + out.write("Количество путей решения: " + solution.getNumberOfRoutes()); + // Numero de rutas de la solucion: out.newLine(); out.newLine(); - out.write("Rutas conseguidas:"); + out.write("Достигнутые маршруты:"); + // Rutas conseguidas: out.newLine(); out.newLine(); out.write(solution.getRoutes()); @@ -96,22 +165,28 @@ private static void fillMatrix(double[][] coord) throws Exception { */ public static void main(String[] args) { if (args.length != 1) { - System.err.println("Numero de argumentos invalidos"); + System.err.println("Неправильное количество аргументов"); + // Numero de argumentos invalidos System.exit(1); } String InstanceName = args[0]; try { - LoadData(InstanceName); + //LoadData(InstanceName); + LoadData_new(InstanceName); algorithm = new IteratedLocalSearchAlgorithm(vrp); ILSSolutionSet solution = algorithm.execute(); writeFile(solution, InstanceName); - System.out.println("Ejecución finalizada"); - System.out.println("Mejor distancia (CON DROPTIME): " + System.out.println("Выполнение завершено"); + // Ejecución finalizada + System.out.println("Лучшее расстояние (с DROPTIME): " + solution.getBestDistance()); - System.out.println("Mejor distancia (SIN DROPTIME): " + // Mejor distancia (CON DROPTIME): + System.out.println("Лучшее расстояние (без DROPTIME): " + solution.getTotaldistance()); + // Mejor distancia (SIN DROPTIME): } catch (Exception e) { - System.out.println("Excepcion atrapada en Main"); + System.out.println("Ошибка в main"); + // Excepcion atrapada en Main e.printStackTrace(System.out); System.exit(1); }