Skip to content

Commit 7d1f470

Browse files
committed
modernize
1 parent 3c7c4bf commit 7d1f470

14 files changed

Lines changed: 43 additions & 69 deletions

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,6 @@ dist
1313
build
1414
.DS_Store
1515
uv.lock
16+
coverage.xml
17+
.coverage
18+
sort-by-distance-output.csv

allocator/cluster_kahip.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Allocator by Karlsruhe High Quality Partitioning (KaHIP)
64
"""

allocator/cluster_kmeans.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Allocator by K-means
64
"""

allocator/compare_kahip_kmeans.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
32

43
import sys
54
import shlex
@@ -60,16 +59,14 @@ def main(argv=sys.argv[1:]):
6059
buffoon = '--buffoon' if args.buffoon else ''
6160
balance_edges = '--balance-edges' if args.balance_edges else ''
6261

63-
kahip_cmd = "python -m allocator.cluster_kahip -n {k:d} --n-closest {n_closest:d} \
64-
{buffoon:s} {balance_edges:s} {input:s} -o tmpkahip{k:d}.csv -d {dfunc:s} \
65-
".format(k=n_clusters, input=args.input, n_closest=args.n_closest,
66-
buffoon=buffoon, balance_edges=balance_edges, dfunc=args.distance_func)
62+
kahip_cmd = (f"python -m allocator.cluster_kahip -n {n_clusters:d} --n-closest {args.n_closest:d} "
63+
f"{buffoon} {balance_edges} {args.input} -o tmpkahip{n_clusters:d}.csv -d {args.distance_func}")
6764

68-
print(("KaHIP command line '{:s}'".format(kahip_cmd)))
65+
print(f"KaHIP command line '{kahip_cmd}'")
6966
out, err = execute(kahip_cmd)
70-
print(("Output: {:s}".format(out)))
67+
print(f"Output: {out}")
7168

72-
bdf = pd.read_csv('tmpkahip{k:d}.csv'.format(k=n_clusters))
69+
bdf = pd.read_csv(f'tmpkahip{n_clusters:d}.csv')
7370

7471
buffoon_w = []
7572
for cluster_id in sorted(bdf.assigned_points.unique()):
@@ -92,15 +89,14 @@ def main(argv=sys.argv[1:]):
9289
adf = pd.DataFrame(buffoon_w, columns=['label', 'n', 'graph_weight',
9390
'mst_weight'])
9491

95-
kmean_cmd = 'python -m allocator.cluster_kmeans -n {k:d} {input:s} \
96-
-o tmpkmean{k:d}.csv -d {dfunc:s}'.format(k=n_clusters, input=args.input,
97-
dfunc=args.distance_func)
92+
kmean_cmd = (f'python -m allocator.cluster_kmeans -n {n_clusters:d} {args.input} '
93+
f'-o tmpkmean{n_clusters:d}.csv -d {args.distance_func}')
9894

99-
print(("K-mean command line '{:s}'".format(kmean_cmd)))
95+
print(f"K-mean command line '{kmean_cmd}'")
10096
out, err = execute(kmean_cmd)
101-
print(("Output: {:s}".format(out)))
97+
print(f"Output: {out}")
10298

103-
kdf = pd.read_csv('tmpkmean{k:d}.csv'.format(k=n_clusters))
99+
kdf = pd.read_csv(f'tmpkmean{n_clusters:d}.csv')
104100

105101
kmean_w = []
106102
for cluster_id in sorted(kdf.assigned_points.unique()):

allocator/distance_matrix.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Distance Matrix
33
"""
4+
from __future__ import annotations
45

56
import os
67
import math
@@ -20,15 +21,15 @@
2021
MAX_DISTANCE_MATRIX_SIZE = 100
2122

2223

23-
def pairwise_distances(X, Y=None):
24+
def pairwise_distances(X: np.ndarray, Y: np.ndarray | None = None) -> np.ndarray:
2425
"""Pairwise euclidean distance calculation
2526
"""
2627
if Y is None:
2728
Y = X
2829
return np.sqrt(((Y - X[:, np.newaxis])**2).sum(axis=2))
2930

3031

31-
def latlon2xy(lat, lon):
32+
def latlon2xy(lat: float, lon: float) -> list[float]:
3233
"""Transform lat/lon to UTM coordinate
3334
3435
Args:
@@ -44,7 +45,7 @@ def latlon2xy(lat, lon):
4445
return [utm_x, utm_y]
4546

4647

47-
def xy2latlog(x, y, zone_number, zone_letter=None):
48+
def xy2latlog(x: float, y: float, zone_number: int, zone_letter: str | None = None) -> tuple[float, float]:
4849
"""Transform x, y coordinate to lat/lon coordinate
4950
5051
Args:
@@ -57,10 +58,10 @@ def xy2latlog(x, y, zone_number, zone_letter=None):
5758
5859
"""
5960
lat, lon = utm.to_latlon(x, y, zone_number, zone_letter)
60-
return [lat, lon]
61+
return (lat, lon)
6162

6263

63-
def euclidean_distance_matrix(X, Y=None):
64+
def euclidean_distance_matrix(X: np.ndarray, Y: np.ndarray | None = None) -> np.ndarray:
6465
"""Euclidean distance matrix calculation
6566
"""
6667
if Y is None:
@@ -71,7 +72,7 @@ def euclidean_distance_matrix(X, Y=None):
7172
return pairwise_distances(X, Y)
7273

7374

74-
def haversine_distance_matrix(X, Y=None):
75+
def haversine_distance_matrix(X: np.ndarray, Y: np.ndarray | None = None) -> np.ndarray:
7576
"""Harversine distance matrix calculation
7677
"""
7778
if Y is None:

allocator/shortest_path_gm.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Shortest path using Google Direction API
64
"""

allocator/shortest_path_mst_tsp.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Shortest path using approximate TSP (Christofides's algorithm)
64
"""

allocator/shortest_path_ortools.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Shortest path using Google's ortools TSP solver
64
"""
5+
from __future__ import annotations
76

87
import os
98
import sys
109
import argparse
10+
from typing import Any
1111
from random import randint
1212

1313
import pandas as pd
14+
import numpy as np
1415

1516
from ortools.constraint_solver import pywrapcp
1617
# You need to import routing_enums_pb2 after pywrapcp!
@@ -24,10 +25,10 @@
2425
logger = get_logger(__name__)
2526

2627

27-
class DistanceMatrix(object):
28-
"""Random matrix."""
29-
30-
def __init__(self, A, args):
28+
class DistanceMatrix:
29+
"""Distance matrix for TSP calculations."""
30+
31+
def __init__(self, A: np.ndarray, args) -> None:
3132
"""Initialize distance matrix."""
3233
if args.distance_func == 'euclidean':
3334
distances = euclidean_distance_matrix(A)
@@ -38,7 +39,7 @@ def __init__(self, A, args):
3839
chunksize=args.osrm_max_table_size,
3940
osrm_base_url=args.osrm_base_url)
4041
(nx, ny) = distances.shape
41-
self.matrix = {}
42+
self.matrix: dict[int, dict[int, float]] = {}
4243
for from_node in range(nx):
4344
self.matrix[from_node] = {}
4445
for to_node in range(ny):
@@ -48,7 +49,7 @@ def __init__(self, A, args):
4849
self.matrix[from_node][to_node] = distances[from_node,
4950
to_node]
5051

51-
def Distance(self, from_node, to_node):
52+
def Distance(self, from_node: int, to_node: int) -> float:
5253
return self.matrix[from_node][to_node]
5354

5455

allocator/shortest_path_osrm.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Shortest path using OSRM trip API
64
"""

allocator/sort_by_distance.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
42
"""
53
Allocator by sorting distance from known worker location
64
"""

0 commit comments

Comments
 (0)