Sfoglia il codice sorgente

added two algorithms (Miguel)

wpfat23-5 2 anni fa
parent
commit
f56e6757b0

+ 1 - 1
mvnw

@@ -30,7 +30,7 @@
 #   M2_HOME - location of maven2's installed home dir
 #   MAVEN_OPTS - parameters passed to the Java VM when running Maven
 #     e.g. to debug Maven itself, use
-#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=lon,suspend=lon,address=8000
 #   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
 # ----------------------------------------------------------------------------
 

+ 1 - 1
mvnw.cmd

@@ -29,7 +29,7 @@
 @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
 @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
 @REM     e.g. to debug Maven itself, use
-@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=lon,suspend=lon,address=8000
 @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
 @REM ----------------------------------------------------------------------------
 

+ 69 - 12
src/main/java/com/deliveryproject/easydelivery/MainController.java

@@ -1,11 +1,14 @@
 package com.deliveryproject.easydelivery;
 
+import com.deliveryproject.easydelivery.Models.Coordinate;
 import com.deliveryproject.easydelivery.Models.OSMRClass.Intersection;
 import com.deliveryproject.easydelivery.Models.OSMRClass.Root;
 import com.deliveryproject.easydelivery.Models.OSMRClass.Step;
+import com.deliveryproject.easydelivery.Utils.AntColony;
+import com.deliveryproject.easydelivery.Utils.SimulatedAnnealing;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.springframework.web.bind.annotation.*;
-import com.deliveryproject.easydelivery.Models.Coordinate;
+
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
@@ -52,14 +55,15 @@ public class MainController {
                 location.add(intersection.location.get(0));
                 coordinates.add(location);
             }
+
         }
         System.out.println(coordinates);
         return coordinates;
     }
 
-    @GetMapping("/optimize-delivery-route")
+    @RequestMapping("/optimize-delivery-route")
     @ResponseBody
-    public List<Coordinate> optimizeDeliveryRoute(List<Coordinate> coordinates) {
+    public List<Coordinate> optimizeDeliveryRoute(@RequestBody List<Coordinate> coordinates) {
 
         List<Integer> optimizedRoute = new ArrayList<>();
         List<Coordinate> optimizedRouteCoordinates = new ArrayList<>();
@@ -92,6 +96,34 @@ public class MainController {
         return optimizedRouteCoordinates;
     }
 
+    @RequestMapping("/intersections-between-multiple-coordinates/{algorithm}")
+    @ResponseBody
+    public List<Coordinate> getIntersectionsBetweenCoordinates(@PathVariable("algorithm") String algorithm, @RequestBody List<Coordinate> coordinates) throws IOException {
+        List<Coordinate> optimizedRouteCoordinates = null;
+        if (algorithm.equals("Brute-Force")) {
+             optimizedRouteCoordinates = optimizeDeliveryRoute(coordinates);
+            System.out.println("Brute-Force");
+        } else if (algorithm.equals("Ant")){
+            optimizedRouteCoordinates = optimizeDeliveryRouteACO(coordinates);
+            System.out.println("ANT");
+        } else if (algorithm.equals("Annealing")){
+            optimizedRouteCoordinates = optimizeDeliveryRouteAnnealing(coordinates);
+            System.out.println("Annealing");
+        }
+
+        ArrayList<Coordinate> nodes = new ArrayList<>();
+        for (int i = 0; i < optimizedRouteCoordinates.size(); i++) {
+            ArrayList<ArrayList<Double>> nodesBetweenTwoCoordinates;
+            if (i == optimizedRouteCoordinates.size() - 1) nodesBetweenTwoCoordinates = getNodesBetweenTwoCoordinates(optimizedRouteCoordinates.get(i).lon, optimizedRouteCoordinates.get(i).lat,optimizedRouteCoordinates.get(0).lon, optimizedRouteCoordinates.get(0).lat);
+            else nodesBetweenTwoCoordinates = getNodesBetweenTwoCoordinates(optimizedRouteCoordinates.get(i).lon, optimizedRouteCoordinates.get(i).lat,optimizedRouteCoordinates.get(i+1).lon, optimizedRouteCoordinates.get(i+1).lat);
+            System.out.println("Drop off");
+            for (ArrayList <Double> node: nodesBetweenTwoCoordinates) {
+                nodes.add(new Coordinate(node.get(0), node.get(1)));
+            }
+        }
+        return nodes;
+    }
+
     @GetMapping("/optimize-delivery-route-aco")
     @ResponseBody
     public List<Coordinate> optimizeDeliveryRouteACO(@RequestBody List<Coordinate> coordinates) throws IOException {
@@ -111,10 +143,10 @@ public class MainController {
                 if (i == j) {
                     distanceMatrix[i][j] = 0.0;
                 } else {
-                    double x1 = coordinates.get(i).getX();
-                    double y1 = coordinates.get(i).getY();
-                    double x2 = coordinates.get(j).getX();
-                    double y2 = coordinates.get(j).getY();
+                    double x1 = coordinates.get(i).getLat();
+                    double y1 = coordinates.get(i).getLon();
+                    double x2 = coordinates.get(j).getLat();
+                    double y2 = coordinates.get(j).getLon();
 
                     double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                     distanceMatrix[i][j] = distance;
@@ -144,10 +176,10 @@ public class MainController {
 
             // Get the nodes between the current and next coordinates
             ArrayList<ArrayList<Double>> nodesBetweenCoordinates = getNodesBetweenTwoCoordinates(
-                    currentCoordinate.getX(),
-                    currentCoordinate.getY(),
-                    nextCoordinate.getX(),
-                    nextCoordinate.getY()
+                    currentCoordinate.getLat(),
+                    currentCoordinate.getLon(),
+                    nextCoordinate.getLat(),
+                    nextCoordinate.getLon()
             );
 
             // Convert the nodes to Coordinate objects and add them to the optimizedRoute
@@ -167,7 +199,7 @@ public class MainController {
     private double calculateDistance(Coordinate c1, Coordinate c2) {
         ArrayList<ArrayList<Double>> nodes;
         try {
-            nodes = getNodesBetweenTwoCoordinates(c1.x, c1.y, c2.x, c2.y);
+            nodes = getNodesBetweenTwoCoordinates(c1.lon, c1.lat, c2.lon, c2.lat);
         } catch (IOException e) {
             e.printStackTrace();
             return Double.MAX_VALUE;
@@ -187,6 +219,31 @@ public class MainController {
         return sumDistance;
     }
 
+    @GetMapping("/optimize-delivery-route-annealing")
+    @ResponseBody
+    public List<Coordinate> optimizeDeliveryRouteAnnealing(List<Coordinate> coordinates) {
+        SimulatedAnnealing annealing = new SimulatedAnnealing();
+
+        List<Coordinate> currentSolution = new ArrayList<>(coordinates);
+
+        double initialTemperature = 500.0; // Initial temperature
+        double coolingRate = 0.85; // Cooling rate
+        int numIterations = 1000; // Number of iterations
+        currentSolution = annealing.optimize(currentSolution, initialTemperature, coolingRate, numIterations);
+
+        return currentSolution;
+    }
+
+
+
+
+
+
+
+
+
+
+
 }
 
 

+ 12 - 12
src/main/java/com/deliveryproject/easydelivery/Models/Coordinate.java

@@ -1,26 +1,26 @@
 package com.deliveryproject.easydelivery.Models;
 
 public class Coordinate {
-    public double x;
-    public double y;
+    public double lat;
+    public double lon;
     public Coordinate(double lat, double lon) {
-        this.x = lat;
-        this.y = lon;
+        this.lat = lat;
+        this.lon = lon;
     }
 
-    public double getX() {
-        return x;
+    public double getLat() {
+        return lat;
     }
 
-    public void setX(double x) {
-        this.x = x;
+    public void setLat(double lat) {
+        this.lat = lat;
     }
 
-    public double getY() {
-        return y;
+    public double getLon() {
+        return lon;
     }
 
-    public void setY(double y) {
-        this.y = y;
+    public void setLon(double lon) {
+        this.lon = lon;
     }
 }

+ 13 - 2
src/main/java/com/deliveryproject/easydelivery/PostConstructInit.java

@@ -13,6 +13,7 @@ import java.time.LocalDateTime;
 import java.time.Month;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 @Component
@@ -26,16 +27,26 @@ public class PostConstructInit {
     @Autowired
     PacketController packetController;
 
+    List<String> addressList = new ArrayList<>();
+
+
     @PostConstruct
     public void init(){
+        addressList.add("Sukcesja");
+        addressList.add("Manufaktura");
+        addressList.add("Zdrowie");
+        addressList.add("Przędzalniana");
+        addressList.add("Zarzewska");
+
+
         AppUser appUser = new AppUser();
         appUser.setName("user2");
         appUserController.createUser(appUser);
-        for (int i = 0; i<10; i++){
+        for (int i = 0; i<5; i++){
             Delivery delivery = new Delivery();
             delivery.setDeliveryTime(LocalDateTime.of(2024,
                     Month.JULY, 29, 19, 30, 40));
-            delivery.setDeliveryAddress(RandomAddressGenerator.generateRandomAddress());
+            delivery.setDeliveryAddress(addressList.get(i));
             delivery.setRecipientName("Adam Nowak");
             Packet packet = new Packet("Packet description", "Packet name");
             ArrayList<Packet> packets = new ArrayList<>();

+ 1 - 1
src/main/java/com/deliveryproject/easydelivery/AntColony.java → src/main/java/com/deliveryproject/easydelivery/Utils/AntColony.java

@@ -1,4 +1,4 @@
-package com.deliveryproject.easydelivery;
+package com.deliveryproject.easydelivery.Utils;
 
 import java.util.ArrayList;
 import java.util.List;

+ 1 - 1
src/main/java/com/deliveryproject/easydelivery/Utils/RandomAddressGenerator.java

@@ -18,7 +18,7 @@ public class RandomAddressGenerator {
         String streetName = streetNames[random.nextInt(streetNames.length)];
         String postalCode = postalCodes[random.nextInt(postalCodes.length)];
 
-        int buildingNumber = random.nextInt(100) + 1;
+        int buildingNumber = random.nextInt(10) + 1;
 
 
         return buildingNumber + " " + streetName + ", " + postalCode + " " + cities[0];

+ 97 - 0
src/main/java/com/deliveryproject/easydelivery/Utils/SimulatedAnnealing.java

@@ -0,0 +1,97 @@
+package com.deliveryproject.easydelivery.Utils;
+import com.deliveryproject.easydelivery.Models.Coordinate;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Collections;
+import java.util.Random;
+public class SimulatedAnnealing {
+    private static final Random random = new Random();
+
+    public List<Coordinate> optimize(List<Coordinate> initialSolution, double initialTemperature, double coolingRate, int numIterations) {
+        List<Coordinate> currentSolution = new ArrayList<>(initialSolution);
+        List<Coordinate> bestSolution = new ArrayList<>(currentSolution);
+
+        double currentObjective = calculateObjective(currentSolution);
+        double bestObjective = currentObjective;
+
+        double currentTemperature = initialTemperature;
+
+        for (int iteration = 0; iteration < numIterations; iteration++) {
+            List<Coordinate> newSolution = generateNeighbor(currentSolution);
+
+            double newObjective = calculateObjective(newSolution);
+
+            if (acceptSolution(currentObjective, newObjective, currentTemperature)) {
+                currentSolution = newSolution;
+                currentObjective = newObjective;
+
+                if (newObjective < bestObjective) {
+                    bestSolution = newSolution;
+                    bestObjective = newObjective;
+                }
+            }
+
+            currentTemperature = updateTemperature(currentTemperature, coolingRate);
+        }
+
+        return bestSolution;
+    }
+
+    private List<Coordinate> generateNeighbor(List<Coordinate> solution) {
+        List<Coordinate> neighbor = new ArrayList<>(solution);
+
+        int size = neighbor.size();
+
+        int index1 = random.nextInt(size);
+        int index2 = random.nextInt(size);
+
+        Collections.swap(neighbor, index1, index2);
+
+        return neighbor;
+    }
+
+    private double calculateObjective(List<Coordinate> solution) {
+        double totalDistance = 0.0;
+
+        int size = solution.size();
+
+        for (int i = 0; i < size - 1; i++) {
+            Coordinate currentCoordinate = solution.get(i);
+            Coordinate nextCoordinate = solution.get(i + 1);
+
+            double distance = calculateDistance(currentCoordinate, nextCoordinate);
+            totalDistance += distance;
+        }
+
+        return totalDistance;
+    }
+
+    private boolean acceptSolution(double currentObjective, double newObjective, double temperature) {
+        if (newObjective < currentObjective) {
+            return true;
+        } else {
+            double acceptanceProbability = Math.exp((currentObjective - newObjective) / temperature);
+            return random.nextDouble() < acceptanceProbability;
+        }
+    }
+
+    private double updateTemperature(double currentTemperature, double coolingRate) {
+        return currentTemperature * (1 - coolingRate);
+    }
+
+    private double calculateDistance(Coordinate coordinate1, Coordinate coordinate2) {
+        // Euclidean distance
+        double lon1 = coordinate1.getLon();
+        double lat1 = coordinate1.getLat();
+        double lon2 = coordinate2.getLon();
+        double lat2 = coordinate2.getLat();
+
+        double lonDiff = lon2 - lon1;
+        double latDiff = lat2 - lat1;
+
+        double distance = Math.sqrt(lonDiff * lonDiff + latDiff * latDiff);
+
+        return distance;
+    }
+}