Skip to content

Commit 16a6997

Browse files
committed
run lint
1 parent e887f71 commit 16a6997

File tree

2 files changed

+35
-50
lines changed

2 files changed

+35
-50
lines changed

backend/python/app/services/implementations/sweep_algorithm_test.py

Lines changed: 17 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -12,41 +12,29 @@
1212
import os
1313
import sys
1414

15-
# Ensure the backend root is on path so "app" is importable (works when run as script or -m)
16-
_backend_root = os.path.abspath(
17-
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)
18-
)
19-
if _backend_root not in sys.path:
20-
sys.path.insert(0, _backend_root)
15+
sys.path.insert(0, "/app")
2116

2217
import matplotlib.pyplot as plt
2318
import pandas as pd
2419
import seaborn as sns
25-
2620
from sqlmodel import Session, create_engine, func, select
2721

2822
from app.models.location import Location
29-
from app.models.location_group import LocationGroup # noqa: F401
30-
from app.models.route import Route # noqa: F401
31-
from app.models.route_group import RouteGroup # noqa: F401
32-
from app.models.route_group_membership import RouteGroupMembership # noqa: F401
3323
from app.models.route_stop import RouteStop # noqa: F401
3424
from app.models.system_settings import SystemSettings
3525
from app.services.implementations.sweep_clustering import (
3626
SweepClusteringAlgorithm,
3727
)
38-
from app.utilities.geocoding import geocode
3928

4029
# Use the same connection string as seed_database.py
4130
DATABASE_URL = "postgresql://postgres:postgres@f4k_db:5432/f4k"
4231

4332
# Configure number of locations pulled from csv for testing
4433
LOCATIONS_COUNT = 18
4534

46-
# Sweep clustering uses these in the loop; both must be set (use high box limit to avoid splitting by boxes).
4735
NUM_CLUSTERS = 10
48-
MAX_LOCATIONS_PER_CLUSTER = 10
49-
MAX_BOXES_PER_CLUSTER = 9999
36+
MAX_LOCATIONS_PER_CLUSTER = 5
37+
MAX_BOXES_PER_CLUSTER = 50
5038

5139

5240
async def main() -> None:
@@ -69,32 +57,14 @@ async def main() -> None:
6957
print("Not enough locations with coordinates to cluster!")
7058
return
7159

72-
# Warehouse coordinates: from SystemSettings (lat/lon or geocode address) or centroid fallback
7360
warehouse_lat: float
7461
warehouse_lon: float
7562
system_settings = session.exec(select(SystemSettings).limit(1)).first()
76-
if (
77-
system_settings
78-
and system_settings.warehouse_latitude is not None
79-
and system_settings.warehouse_longitude is not None
80-
):
81-
warehouse_lat = system_settings.warehouse_latitude
82-
warehouse_lon = system_settings.warehouse_longitude
83-
print(f"Using warehouse from system settings: ({warehouse_lat}, {warehouse_lon})\n")
84-
elif system_settings and system_settings.warehouse_location:
85-
coords = await geocode(system_settings.warehouse_location)
86-
if coords is not None:
87-
warehouse_lat = coords["lat"]
88-
warehouse_lon = coords["lng"]
89-
print(f"Geocoded warehouse: ({warehouse_lat}, {warehouse_lon})\n")
90-
else:
91-
warehouse_lat = sum(loc.latitude for loc in locations) / len(locations)
92-
warehouse_lon = sum(loc.longitude for loc in locations) / len(locations)
93-
print(f"Geocode failed; using centroid: ({warehouse_lat}, {warehouse_lon})\n")
94-
else:
95-
warehouse_lat = sum(loc.latitude for loc in locations) / len(locations)
96-
warehouse_lon = sum(loc.longitude for loc in locations) / len(locations)
97-
print(f"No warehouse in system settings; using centroid: ({warehouse_lat}, {warehouse_lon})\n")
63+
warehouse_lat = system_settings.warehouse_latitude
64+
warehouse_lon = system_settings.warehouse_longitude
65+
print(
66+
f"Using warehouse from system settings: ({warehouse_lat}, {warehouse_lon})\n"
67+
)
9868

9969
total_boxes = sum(loc.num_boxes for loc in locations)
10070

@@ -151,7 +121,12 @@ async def main() -> None:
151121
print(f" Boxes: {loc.num_boxes}")
152122
cluster_boxes += loc.num_boxes
153123
df_rows.append(
154-
{"name": name, "long": loc.longitude, "lat": loc.latitude, "group": i}
124+
{
125+
"name": name,
126+
"long": loc.longitude,
127+
"lat": loc.latitude,
128+
"group": i,
129+
}
155130
)
156131

157132
print(f"\n Total boxes in cluster: {cluster_boxes}")
@@ -176,7 +151,9 @@ async def main() -> None:
176151
print("\n" + "=" * 60)
177152
print("Summary:")
178153
print(f" Total clusters: {len(clusters)}")
179-
print(f" Number of locations in each cluster: {[len(c) for c in clusters]}")
154+
print(
155+
f" Number of locations in each cluster: {[len(c) for c in clusters]}"
156+
)
180157
print(f" Total locations clustered: {sum(len(c) for c in clusters)}")
181158

182159
except ValueError as e:

backend/python/app/services/implementations/sweep_clustering.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
from __future__ import annotations
22

3+
import math
4+
import time
35
from typing import TYPE_CHECKING
46

57
from app.services.protocols.clustering_algorithm import (
68
ClusteringAlgorithmProtocol,
79
)
810

9-
import math
10-
import time
11-
1211
if TYPE_CHECKING:
1312
from app.models.location import Location
1413

14+
1515
class LocationLatitudeError(Exception):
1616
"""Raised when a location doesn't have a latitude."""
1717

@@ -23,11 +23,13 @@ class LocationLongitudeError(Exception):
2323

2424
pass
2525

26+
2627
class TimeoutError(Exception):
2728
"""Raised when an operation exceeds its timeout limit."""
2829

2930
pass
3031

32+
3133
class SweepClusteringAlgorithm(ClusteringAlgorithmProtocol):
3234
"""Simple mock clustering algorithm that splits locations into clusters.
3335
@@ -104,6 +106,7 @@ def calculate_distance_squared(location: Location) -> float | None:
104106
lat_difference = location.latitude - warehouse_lat
105107
lon_difference = location.longitude - warehouse_lon
106108
return lon_difference**2 + lat_difference**2
109+
107110
if len(locations) == 0:
108111
raise ValueError("locations list cannot be empty")
109112

@@ -142,20 +145,25 @@ def calculate_distance_squared(location: Location) -> float | None:
142145
distance_squared = calculate_distance_squared(location)
143146
locations_with_angles.append((location, angle, distance_squared))
144147

145-
sorted_locations = sorted(locations_with_angles, key=lambda location: (location[1], location[2]))
146-
148+
sorted_locations = sorted(
149+
locations_with_angles, key=lambda location: (location[1], location[2])
150+
)
147151

148-
for loc, angle, distance in sorted_locations:
152+
for loc, _angle, _distance in sorted_locations:
149153
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-
154+
would_exceed_locations = (
155+
current_location_count + 1 > max_locations_per_cluster
156+
)
157+
would_exceed_boxes = (
158+
current_box_count + loc.num_boxes > max_boxes_per_cluster
159+
)
160+
153161
if current_cluster and (would_exceed_locations or would_exceed_boxes):
154162
clusters.append(current_cluster)
155163
current_cluster = []
156164
current_location_count = 0
157165
current_box_count = 0
158-
166+
159167
current_cluster.append(loc)
160168
current_location_count += 1
161169
current_box_count += loc.num_boxes

0 commit comments

Comments
 (0)