|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +from app.services.protocols.clustering_algorithm import ( |
| 6 | + ClusteringAlgorithmProtocol, |
| 7 | +) |
| 8 | + |
| 9 | +import math |
| 10 | +import time |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from app.models.location import Location |
| 14 | + |
| 15 | +class LocationLatitudeError(Exception): |
| 16 | + """Raised when a location doesn't have a latitude.""" |
| 17 | + |
| 18 | + pass |
| 19 | + |
| 20 | + |
| 21 | +class LocationLongitudeError(Exception): |
| 22 | + """Raised when a location doesn't have a longitude.""" |
| 23 | + |
| 24 | + pass |
| 25 | + |
| 26 | +class TimeoutError(Exception): |
| 27 | + """Raised when an operation exceeds its timeout limit.""" |
| 28 | + |
| 29 | + pass |
| 30 | + |
| 31 | +class SweepClusteringAlgorithm(ClusteringAlgorithmProtocol): |
| 32 | + """Simple mock clustering algorithm that splits locations into clusters. |
| 33 | +
|
| 34 | + This is a pure function with no database interaction. It distributes |
| 35 | + locations across clusters while respecting max_locations_per_cluster and |
| 36 | + max_boxes_per_cluster constraints. |
| 37 | + """ |
| 38 | + |
| 39 | + async def cluster_locations( |
| 40 | + self, |
| 41 | + locations: list[Location], |
| 42 | + num_clusters: int, |
| 43 | + warehouse_lat: float, |
| 44 | + warehouse_lon: float, |
| 45 | + max_locations_per_cluster: int | None = None, |
| 46 | + max_boxes_per_cluster: int | None = None, |
| 47 | + timeout_seconds: float | None = None, |
| 48 | + ) -> list[list[Location]]: |
| 49 | + """Split locations into clusters while respecting box constraints. |
| 50 | +
|
| 51 | + Args: |
| 52 | + locations: List of locations to cluster |
| 53 | + num_clusters: Target number of clusters to create |
| 54 | + max_locations_per_cluster: Optional maximum number of locations |
| 55 | + per cluster. If provided, validates that the clustering is |
| 56 | + possible and raises an error if violated. |
| 57 | + max_boxes_per_cluster: Optional maximum number of boxes per cluster. |
| 58 | + If provided, validates that the clustering is possible and |
| 59 | + raises an error if violated. |
| 60 | + timeout_seconds: Optional timeout in seconds. Not enforced in this |
| 61 | + mock implementation. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + List of clusters, where each cluster is a list of locations |
| 65 | +
|
| 66 | + Raises: |
| 67 | + ValueError: If the clustering parameters are invalid or cannot |
| 68 | + be satisfied |
| 69 | + """ |
| 70 | + |
| 71 | + start_time = time.time() |
| 72 | + |
| 73 | + def check_timeout() -> None: |
| 74 | + if timeout_seconds is not None: |
| 75 | + elapsed = time.time() - start_time |
| 76 | + if elapsed > timeout_seconds: |
| 77 | + raise TimeoutError( |
| 78 | + f"Route generation exceeded timeout of {timeout_seconds}s " |
| 79 | + f"(elapsed: {elapsed:.2f}s)" |
| 80 | + ) |
| 81 | + |
| 82 | + def calculate_angle_from_warehouse(location: Location) -> float | None: |
| 83 | + if location.latitude is None: |
| 84 | + raise LocationLatitudeError( |
| 85 | + f"Location {location.location_id} is missing latitude." |
| 86 | + ) |
| 87 | + if location.longitude is None: |
| 88 | + raise LocationLongitudeError( |
| 89 | + f"Location {location.location_id} is missing longitude." |
| 90 | + ) |
| 91 | + lat_difference = location.latitude - warehouse_lat |
| 92 | + lon_difference = location.longitude - warehouse_lon |
| 93 | + return math.atan2(lat_difference, lon_difference) % math.tau |
| 94 | + |
| 95 | + def calculate_distance_squared(location: Location) -> float | None: |
| 96 | + if location.latitude is None: |
| 97 | + raise LocationLatitudeError( |
| 98 | + f"Location {location.location_id} is missing latitude." |
| 99 | + ) |
| 100 | + if location.longitude is None: |
| 101 | + raise LocationLongitudeError( |
| 102 | + f"Location {location.location_id} is missing longitude." |
| 103 | + ) |
| 104 | + lat_difference = location.latitude - warehouse_lat |
| 105 | + lon_difference = location.longitude - warehouse_lon |
| 106 | + return lon_difference**2 + lat_difference**2 |
| 107 | + if len(locations) == 0: |
| 108 | + raise ValueError("locations list cannot be empty") |
| 109 | + |
| 110 | + if num_clusters < 1: |
| 111 | + raise ValueError("num_clusters must be at least 1") |
| 112 | + |
| 113 | + # Calculate base cluster size and validate constraints |
| 114 | + total_locations = len(locations) |
| 115 | + base_cluster_size = total_locations // num_clusters |
| 116 | + remainder = total_locations % num_clusters |
| 117 | + |
| 118 | + if base_cluster_size == 0: |
| 119 | + raise ValueError( |
| 120 | + f"Cannot create {num_clusters} clusters: not enough locations" |
| 121 | + ) |
| 122 | + |
| 123 | + # The largest cluster will have base_cluster_size + 1 if remainder > 0 |
| 124 | + max_cluster_size = base_cluster_size + (1 if remainder > 0 else 0) |
| 125 | + if max_locations_per_cluster and max_cluster_size > max_locations_per_cluster: |
| 126 | + raise ValueError( |
| 127 | + f"Cannot create {num_clusters} clusters with max " |
| 128 | + f"{max_locations_per_cluster} locations per cluster. " |
| 129 | + f"Required cluster size would be up to {max_cluster_size}." |
| 130 | + ) |
| 131 | + |
| 132 | + # Distribute locations while respecting constraints |
| 133 | + clusters: list[list[Location]] = [] |
| 134 | + current_location_count = 0 |
| 135 | + current_box_count = 0 |
| 136 | + current_cluster = [] |
| 137 | + |
| 138 | + locations_with_angles = [] |
| 139 | + for location in locations: |
| 140 | + check_timeout() |
| 141 | + angle = calculate_angle_from_warehouse(location) |
| 142 | + distance_squared = calculate_distance_squared(location) |
| 143 | + locations_with_angles.append((location, angle, distance_squared)) |
| 144 | + |
| 145 | + sorted_locations = sorted(locations_with_angles, key=lambda location: (location[1], location[2])) |
| 146 | + |
| 147 | + |
| 148 | + for loc, angle, distance in sorted_locations: |
| 149 | + check_timeout() |
| 150 | + would_exceed_locations = current_location_count + 1 > max_locations_per_cluster |
| 151 | + would_exceed_boxes = current_box_count + loc.num_boxes > max_boxes_per_cluster |
| 152 | + |
| 153 | + if current_cluster and (would_exceed_locations or would_exceed_boxes): |
| 154 | + clusters.append(current_cluster) |
| 155 | + current_cluster = [] |
| 156 | + current_location_count = 0 |
| 157 | + current_box_count = 0 |
| 158 | + |
| 159 | + current_cluster.append(loc) |
| 160 | + current_location_count += 1 |
| 161 | + current_box_count += loc.num_boxes |
| 162 | + |
| 163 | + if current_cluster: |
| 164 | + clusters.append(current_cluster) |
| 165 | + |
| 166 | + return clusters |
0 commit comments