MainController.java 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package com.deliveryproject.easydelivery;
  2. import com.deliveryproject.easydelivery.Models.Coordinate;
  3. import com.deliveryproject.easydelivery.Models.OSMRClass.Intersection;
  4. import com.deliveryproject.easydelivery.Models.OSMRClass.Root;
  5. import com.deliveryproject.easydelivery.Models.OSMRClass.Step;
  6. import com.deliveryproject.easydelivery.Utils.AntColony;
  7. import com.deliveryproject.easydelivery.Utils.SimulatedAnnealing;
  8. import com.fasterxml.jackson.databind.ObjectMapper;
  9. import org.springframework.web.bind.annotation.*;
  10. import java.io.BufferedReader;
  11. import java.io.IOException;
  12. import java.io.InputStreamReader;
  13. import java.net.HttpURLConnection;
  14. import java.net.URL;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. @CrossOrigin
  18. @RestController
  19. public class MainController {
  20. //@PreAuthorize("hasRole('User')")
  21. @GetMapping("/route/nodes")
  22. @ResponseBody
  23. public ArrayList<ArrayList<Double>> getNodesBetweenTwoCoordinates(@RequestParam double lon1, @RequestParam double lat1, @RequestParam double lon2, @RequestParam double lat2) throws IOException {
  24. System.out.println(lon1);
  25. String url = "http://router.project-osrm.org/route/v1/driving/" + lon1 + "," + lat1 + ";" + lon2 + "," + lat2 + "?steps=true&geometries=geojson";
  26. System.out.println(url);
  27. URL osrmEndpoint = new URL(url);
  28. HttpURLConnection connection = (HttpURLConnection) osrmEndpoint.openConnection();
  29. connection.setRequestMethod("GET");
  30. connection.setRequestProperty("Content-Type", "application/json");
  31. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  32. String inputLine;
  33. StringBuilder response = new StringBuilder();
  34. while ((inputLine = in.readLine()) != null) {
  35. response.append(inputLine);
  36. }
  37. in.close();
  38. ObjectMapper om = new ObjectMapper();
  39. Root root = om.readValue(response.toString(), Root.class);
  40. ArrayList<Step> steps = root.routes.get(0).legs.get(0).steps;
  41. ArrayList<ArrayList<Double>> coordinates = new ArrayList<>();
  42. for (Step step : steps) {
  43. ArrayList<Intersection> intersections = step.intersections;
  44. for (Intersection intersection : intersections) {
  45. ArrayList<Double> location = new ArrayList<>();
  46. location.add(intersection.location.get(1));
  47. location.add(intersection.location.get(0));
  48. coordinates.add(location);
  49. }
  50. }
  51. System.out.println(coordinates);
  52. return coordinates;
  53. }
  54. @RequestMapping("/optimize-delivery-route")
  55. @ResponseBody
  56. public List<Coordinate> optimizeDeliveryRoute(@RequestBody List<Coordinate> coordinates) {
  57. List<Integer> optimizedRoute = new ArrayList<>();
  58. List<Coordinate> optimizedRouteCoordinates = new ArrayList<>();
  59. boolean[] visited = new boolean[coordinates.size()];
  60. int currentCoordinateIndex = 0;
  61. optimizedRoute.add(currentCoordinateIndex);
  62. visited[currentCoordinateIndex] = true;
  63. while (optimizedRoute.size() < coordinates.size()) {
  64. double minDistance = Double.MAX_VALUE;
  65. int nearestCoordinateIndex = -1;
  66. for (int i = 0; i < coordinates.size(); i++) {
  67. if (!visited[i]) {
  68. double distance = calculateDistance(coordinates.get(currentCoordinateIndex), coordinates.get(i));
  69. if (distance < minDistance) {
  70. minDistance = distance;
  71. nearestCoordinateIndex = i;
  72. }
  73. }
  74. }
  75. optimizedRoute.add(nearestCoordinateIndex);
  76. visited[nearestCoordinateIndex] = true;
  77. currentCoordinateIndex = nearestCoordinateIndex;
  78. }
  79. for (Integer integer : optimizedRoute) {
  80. optimizedRouteCoordinates.add(coordinates.get(integer));
  81. }
  82. return optimizedRouteCoordinates;
  83. }
  84. @RequestMapping("/intersections-between-multiple-coordinates/{algorithm}")
  85. @ResponseBody
  86. public List<Coordinate> getIntersectionsBetweenCoordinates(@PathVariable("algorithm") String algorithm, @RequestBody List<Coordinate> coordinates) throws IOException {
  87. List<Coordinate> optimizedRouteCoordinates = null;
  88. if (algorithm.equals("Brute-Force")) {
  89. optimizedRouteCoordinates = optimizeDeliveryRoute(coordinates);
  90. System.out.println("Brute-Force");
  91. } else if (algorithm.equals("Ant")){
  92. optimizedRouteCoordinates = optimizeDeliveryRouteACO(coordinates);
  93. System.out.println("ANT");
  94. } else if (algorithm.equals("Annealing")){
  95. optimizedRouteCoordinates = optimizeDeliveryRouteAnnealing(coordinates);
  96. System.out.println("Annealing");
  97. }
  98. ArrayList<Coordinate> nodes = new ArrayList<>();
  99. for (int i = 0; i < optimizedRouteCoordinates.size(); i++) {
  100. ArrayList<ArrayList<Double>> nodesBetweenTwoCoordinates;
  101. if (i == optimizedRouteCoordinates.size() - 1) nodesBetweenTwoCoordinates = getNodesBetweenTwoCoordinates(optimizedRouteCoordinates.get(i).lon, optimizedRouteCoordinates.get(i).lat,optimizedRouteCoordinates.get(0).lon, optimizedRouteCoordinates.get(0).lat);
  102. else nodesBetweenTwoCoordinates = getNodesBetweenTwoCoordinates(optimizedRouteCoordinates.get(i).lon, optimizedRouteCoordinates.get(i).lat,optimizedRouteCoordinates.get(i+1).lon, optimizedRouteCoordinates.get(i+1).lat);
  103. System.out.println("Drop off");
  104. for (ArrayList <Double> node: nodesBetweenTwoCoordinates) {
  105. nodes.add(new Coordinate(node.get(0), node.get(1)));
  106. }
  107. }
  108. return nodes;
  109. }
  110. @GetMapping("/optimize-delivery-route-aco")
  111. @ResponseBody
  112. public List<Coordinate> optimizeDeliveryRouteACO(@RequestBody List<Coordinate> coordinates) throws IOException {
  113. int numAnts = 10;
  114. int numIterations = 100;
  115. double alpha = 1.0;
  116. double beta = 2.0;
  117. double evaporationRate = 0.5;
  118. double initialPheromone = 0.1;
  119. int numStops = coordinates.size();
  120. AntColony antColony = new AntColony(coordinates.size(), numAnts, alpha, beta, evaporationRate, initialPheromone);
  121. // Populate the distance matrix
  122. double[][] distanceMatrix = new double[numStops][numStops];
  123. for (int i = 0; i < numStops; i++) {
  124. for (int j = 0; j < numStops; j++) {
  125. if (i == j) {
  126. distanceMatrix[i][j] = 0.0;
  127. } else {
  128. double x1 = coordinates.get(i).getLat();
  129. double y1 = coordinates.get(i).getLon();
  130. double x2 = coordinates.get(j).getLat();
  131. double y2 = coordinates.get(j).getLon();
  132. double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  133. distanceMatrix[i][j] = distance;
  134. }
  135. }
  136. }
  137. // Set the distance matrix in the AntColony instance
  138. antColony.setDistanceMatrix(distanceMatrix);
  139. antColony.initializePheromoneMatrix();
  140. // Ant colony optimization for the specified number of iterations
  141. for (int iteration = 0; iteration < numIterations; iteration++) {
  142. antColony.constructSolutions();
  143. antColony.updatePheromoneMatrix();
  144. }
  145. // Get the best solution from AntColony and convert it to a list of coordinates
  146. List<Coordinate> bestRoute = antColony.getBestSolution(coordinates);
  147. // Iterate over the bestRoute list
  148. List<Coordinate> optimizedRoute = new ArrayList<>();
  149. for (int i = 0; i < bestRoute.size() - 1; i++) {
  150. Coordinate currentCoordinate = bestRoute.get(i);
  151. Coordinate nextCoordinate = bestRoute.get(i + 1);
  152. // Get the nodes between the current and next coordinates
  153. ArrayList<ArrayList<Double>> nodesBetweenCoordinates = getNodesBetweenTwoCoordinates(
  154. currentCoordinate.getLat(),
  155. currentCoordinate.getLon(),
  156. nextCoordinate.getLat(),
  157. nextCoordinate.getLon()
  158. );
  159. // Convert the nodes to Coordinate objects and add them to the optimizedRoute
  160. for (ArrayList<Double> node : nodesBetweenCoordinates) {
  161. double lon = node.get(1);
  162. double lat = node.get(0);
  163. optimizedRoute.add(new Coordinate(lon, lat));
  164. }
  165. }
  166. // Add the last coordinate to the optimizedRoute
  167. optimizedRoute.add(bestRoute.get(bestRoute.size() - 1));
  168. return optimizedRoute;
  169. }
  170. private double calculateDistance(Coordinate c1, Coordinate c2) {
  171. ArrayList<ArrayList<Double>> nodes;
  172. try {
  173. nodes = getNodesBetweenTwoCoordinates(c1.lon, c1.lat, c2.lon, c2.lat);
  174. } catch (IOException e) {
  175. e.printStackTrace();
  176. return Double.MAX_VALUE;
  177. }
  178. double sumDistance = 0.0;
  179. for (int i = 0; i < nodes.size() - 1; i++) {
  180. ArrayList<Double> current = nodes.get(i);
  181. ArrayList<Double> next = nodes.get(i + 1);
  182. double dx = next.get(0) - current.get(0);
  183. double dy = next.get(1) - current.get(1);
  184. double distance = Math.sqrt(dx * dx + dy * dy);
  185. sumDistance += distance;
  186. }
  187. return sumDistance;
  188. }
  189. @GetMapping("/optimize-delivery-route-annealing")
  190. @ResponseBody
  191. public List<Coordinate> optimizeDeliveryRouteAnnealing(List<Coordinate> coordinates) {
  192. SimulatedAnnealing annealing = new SimulatedAnnealing();
  193. List<Coordinate> currentSolution = new ArrayList<>(coordinates);
  194. double initialTemperature = 500.0; // Initial temperature
  195. double coolingRate = 0.85; // Cooling rate
  196. int numIterations = 1000; // Number of iterations
  197. currentSolution = annealing.optimize(currentSolution, initialTemperature, coolingRate, numIterations);
  198. return currentSolution;
  199. }
  200. }