Skip to content

Commit 4344be6

Browse files
committed
move to logging from printing
1 parent 71b1995 commit 4344be6

7 files changed

Lines changed: 102 additions & 49 deletions

File tree

allocator/__init__.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,53 @@
1+
"""
2+
Allocator package for clustering and routing optimization.
3+
"""
14

5+
import logging
6+
import sys
7+
8+
9+
def setup_logging(level=logging.INFO):
10+
"""
11+
Set up logging configuration for the allocator package.
12+
13+
Args:
14+
level: Logging level (DEBUG, INFO, WARNING, ERROR)
15+
"""
16+
# Create formatter
17+
formatter = logging.Formatter(
18+
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
19+
datefmt='%Y-%m-%d %H:%M:%S'
20+
)
21+
22+
# Get root logger for allocator package
23+
logger = logging.getLogger('allocator')
24+
logger.setLevel(level)
25+
26+
# Remove existing handlers to avoid duplicates
27+
for handler in logger.handlers[:]:
28+
logger.removeHandler(handler)
29+
30+
# Console handler
31+
console_handler = logging.StreamHandler(sys.stdout)
32+
console_handler.setLevel(level)
33+
console_handler.setFormatter(formatter)
34+
logger.addHandler(console_handler)
35+
36+
return logger
37+
38+
39+
def get_logger(name):
40+
"""
41+
Get a logger instance for a specific module.
42+
43+
Args:
44+
name: Module name (typically __name__)
45+
46+
Returns:
47+
Logger instance
48+
"""
49+
return logging.getLogger(f'allocator.{name}')
50+
51+
52+
# Set up default logging
53+
setup_logging()

allocator/distance_matrix.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
import time
88

99
import numpy as np
10+
11+
from allocator import get_logger
12+
logger = get_logger(__name__)
1013
import requests
1114
import googlemaps
1215
import utm
@@ -117,7 +120,7 @@ def osrm_distance_matrix(X, Y=None, chunksize=MAX_DISTANCE_MATRIX_SIZE,
117120
count += 1
118121
r = requests.get(url)
119122
if r.status_code != 200:
120-
print(("OSRM Table API request error: {0:s}".format(r.text)))
123+
logger.error(f"OSRM Table API request error: {r.text}")
121124
break
122125
dm = r.json()['durations']
123126
arr = np.array(dm)
@@ -129,7 +132,7 @@ def osrm_distance_matrix(X, Y=None, chunksize=MAX_DISTANCE_MATRIX_SIZE,
129132
o = c
130133
else:
131134
o = np.concatenate((o, c), axis=0)
132-
print(("Total API requests: {0:d}".format(count)))
135+
logger.info(f"Total API requests: {count}")
133136
return o
134137

135138

@@ -182,8 +185,7 @@ def google_distance_matrix(X, Y=None, api_key=None, duration=True):
182185
try:
183186
matrix = gmaps.distance_matrix(sources, destinations)
184187
except Exception as e:
185-
print(("Google Distance Matrix API error: {0!s}"
186-
.format(e)))
188+
logger.error(f"Google Distance Matrix API error: {e}")
187189
return o
188190
time.sleep(1)
189191
"""
@@ -218,7 +220,7 @@ def google_distance_matrix(X, Y=None, api_key=None, duration=True):
218220
o = c
219221
else:
220222
o = np.concatenate((o, c), axis=0)
221-
print(("Total API requests: {0:d}, elements: {1:d}".format(count, nXY)))
223+
logger.info(f"Total API requests: {count}, elements: {nXY}")
222224
return o
223225

224226

@@ -287,20 +289,20 @@ def google_distance_matrix(X, Y=None, api_key=None, duration=True):
287289
(100.92367939299999, 12.9881022409)]
288290

289291
o = osrm_distance_matrix(A, B, 10)
290-
print((o.sum()))
292+
logger.debug(f"Matrix sum: {o.sum()}")
291293
o = osrm_distance_matrix(A, B, 20)
292-
print((o.sum()))
294+
logger.debug(f"Matrix sum: {o.sum()}")
293295
o = osrm_distance_matrix(A, B, MAX_DISTANCE_MATRIX_SIZE)
294-
print((o.sum()))
296+
logger.debug(f"Matrix sum: {o.sum()}")
295297

296298
api_key = os.environ.get('API_KEY', None)
297299
if api_key:
298300
o = google_distance_matrix(A, B, api_key=api_key)
299-
print((o.sum()))
301+
logger.debug(f"Matrix sum: {o.sum()}")
300302
# Test with origins over 25 elements
301303
o = osrm_distance_matrix(A[:30], B[:3], MAX_DISTANCE_MATRIX_SIZE)
302-
print((o.sum()))
304+
logger.debug(f"Matrix sum: {o.sum()}")
303305
o = google_distance_matrix(A[:30], B[:3], api_key=api_key)
304-
print((o.sum()))
306+
logger.debug(f"Matrix sum: {o.sum()}")
305307
else:
306-
print("Please set Google API key to environment variable `API_KEY`")
308+
logger.warning("Please set Google API key to environment variable `API_KEY`")

allocator/shortest_path_gm.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313

1414
import pandas as pd
1515

16+
from allocator import get_logger
17+
logger = get_logger(__name__)
18+
1619
import googlemaps
1720
import polyline
1821

@@ -40,7 +43,7 @@ def main(argv=sys.argv[1:]):
4043

4144
args = parser.parse_args(argv)
4245

43-
print(args)
46+
logger.debug(f"Arguments: {args}")
4447

4548
df = pd.read_csv(args.input)
4649

@@ -57,7 +60,7 @@ def main(argv=sys.argv[1:]):
5760

5861
output = []
5962
for i, l in enumerate(sorted(df.assigned_points.unique())):
60-
print(("Google Direction API request for #{:d}...".format(l)))
63+
logger.info(f"Google Direction API request for #{l}...")
6164
start = None
6265
adf = df.loc[(df.assigned_points == l), ['start_lat', 'start_long']]
6366
nodes = adf.to_records(index=False).tolist()
@@ -66,7 +69,7 @@ def main(argv=sys.argv[1:]):
6669
tour = []
6770
N = len(nodes)
6871
if N >= 25:
69-
print("WARN: The maximum allowed location is 24 including origin and destination")
72+
logger.warning("The maximum allowed location is 24 including origin and destination")
7073
else:
7174
start = ', '.join([str(x) for x in nodes[0]])
7275
waypoints = [', '.join([str(x) for x in n]) for n in nodes[1:]]
@@ -83,8 +86,6 @@ def main(argv=sys.argv[1:]):
8386
t_dist = 0
8487
t_time = 0
8588
for i, leg in enumerate(legs):
86-
if i == 0:
87-
sloc = leg['start_location']
8889
d = leg['distance']['value']
8990
t_dist += d
9091
t = leg['duration']['value']
@@ -94,7 +95,7 @@ def main(argv=sys.argv[1:]):
9495
t_min = int(t_time / 60 + 1)
9596
tour = [0] + [(i + 1) for i in wp] + [0]
9697
except Exception as e:
97-
print(('ERROR: {0!s}'.format(e)))
98+
logger.error(f'ERROR: {e}')
9899
B = df.loc[df.assigned_points == l,
99100
['segment_id', 'start_lat', 'start_long']]
100101
B.reset_index(drop=True, inplace=True)
@@ -129,7 +130,7 @@ def main(argv=sys.argv[1:]):
129130
if args.save_plot:
130131
fn, fe = os.path.splitext(args.save_plot)
131132
fname = "{:s}-{:d}{:s}".format(fn, l, fe)
132-
print(("Plotting to file '{:s}'".format(fname)))
133+
logger.debug(f"Plotting to file '{fname}'")
133134
fig.savefig(fname)
134135
plt.close()
135136

@@ -145,7 +146,7 @@ def main(argv=sys.argv[1:]):
145146
';'.join([str(p) for p in new_path])])
146147

147148
# save output to file
148-
print(("Save the output file to '{:s}'".format(args.output)))
149+
logger.info(f"Saved output file to '{args.output}'")
149150
odf = pd.DataFrame(output, columns=['worker_id', 'distance', 'duration',
150151
'n', 'path_order'])
151152
odf.to_csv(args.output, index=False)

allocator/shortest_path_ortools.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
import argparse
1111

1212
import pandas as pd
13-
import numpy as np
13+
14+
from allocator import get_logger
15+
logger = get_logger(__name__)
1416

1517
from random import randint
1618

@@ -79,7 +81,7 @@ def ortools_tsp(A, args):
7981
cost = 0
8082
if assignment:
8183
# Solution cost.
82-
print((assignment.ObjectiveValue()))
84+
logger.info(f"Objective value: {assignment.ObjectiveValue()}")
8385
cost = assignment.ObjectiveValue()
8486
# Inspect solution.
8587
# Only one route here; otherwise iterate from 0 to
@@ -93,9 +95,9 @@ def ortools_tsp(A, args):
9395
node = assignment.Value(routing.NextVar(node))
9496
route += '0'
9597
path.append(0)
96-
print(route)
98+
logger.debug(f"Route: {route}")
9799
else:
98-
print('No solution found.')
100+
logger.error('No solution found.')
99101

100102
return cost, path
101103

@@ -116,8 +118,7 @@ def do_save_map(args, label, C):
116118
points = polyline.decode(out['routes'][0]['geometry'])
117119
cost = int(float(out['routes'][0]['distance'] / 1000.0))
118120
duration = out['routes'][0]['duration']
119-
print(("Route map distance: {:.1f}, duration: {:.1f}"
120-
.format(cost, duration)))
121+
logger.info(f"Route map distance: {cost:.1f}, duration: {duration:.1f}")
121122
# FIXME: unused
122123
# legs = out['routes'][0]['legs']
123124
# waypoints = out['waypoints']
@@ -142,10 +143,10 @@ def do_save_map(args, label, C):
142143

143144
fn, fe = os.path.splitext(args.save_map)
144145
fname = "{:s}-{:d}{:s}".format(fn, label, fe)
145-
print(("Save map HTML to file '{:s}'".format(fname)))
146+
logger.debug(f"Saved map HTML to file '{fname}'")
146147
map_osm.save(fname)
147148
except Exception as e:
148-
print(("Error: Cannot save map to file ({!s})".format(e)))
149+
logger.error(f"Error: Cannot save map to file ({e})")
149150

150151

151152
def main(argv=sys.argv[1:]):
@@ -179,7 +180,7 @@ def main(argv=sys.argv[1:]):
179180

180181
args = parser.parse_args(argv)
181182

182-
print(args)
183+
logger.debug(f"Arguments: {args}")
183184

184185
df = pd.read_csv(args.input)
185186

@@ -195,7 +196,7 @@ def main(argv=sys.argv[1:]):
195196
output = []
196197
total_cost = 0
197198
for i, l in enumerate(sorted(df.assigned_points.unique())):
198-
print(("Search TSP path for #{:d}...".format(l)))
199+
logger.info(f"Search TSP path for #{l}...")
199200
adf = df.loc[df.assigned_points == l, ['start_long', 'start_lat']]
200201
A = adf.values
201202
# FIXME: OSRM distance matrix actually isn't distance but it's duration
@@ -211,7 +212,7 @@ def main(argv=sys.argv[1:]):
211212
title = ('TSP: {:d}, Cost: {:0.1f}, N: {:d} ({:s})'
212213
.format(l, cost, N, args.distance_func.title()))
213214

214-
print(title)
215+
logger.info(title)
215216

216217
if args.plot or args.save_plot:
217218
fig = plt.figure(figsize=(16, 16))
@@ -236,7 +237,7 @@ def main(argv=sys.argv[1:]):
236237
if args.save_plot:
237238
fn, fe = os.path.splitext(args.save_plot)
238239
fname = "{:s}-{:d}{:s}".format(fn, l, fe)
239-
print(("Plotting to file '{:s}'".format(fname)))
240+
logger.debug(f"Plotting to file '{fname}'")
240241
fig.savefig(fname)
241242
plt.close()
242243

@@ -253,10 +254,10 @@ def main(argv=sys.argv[1:]):
253254
new_path = path[pos:] + path[:pos]
254255
output.append([l, cost, N, ';'.join([str(p) for p in new_path])])
255256

256-
print(("Total cost: {0:.1f}".format(total_cost)))
257+
logger.info(f"Total cost: {total_cost:.1f}")
257258

258259
# save output to file
259-
print(("Save the output file to '{:s}'".format(args.output)))
260+
logger.info(f"Saved output file to '{args.output}'")
260261
odf = pd.DataFrame(output, columns=['worker_id', 'cost', 'n',
261262
'path_order'])
262263
odf.to_csv(args.output, index=False)

allocator/shortest_path_osrm.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111

1212
import pandas as pd
1313

14+
from allocator import get_logger
15+
logger = get_logger(__name__)
16+
1417
import requests
1518
import polyline
1619

@@ -28,7 +31,7 @@ def osrm_trip(coords, osrm_base_url=None):
2831
a = ';'.join([','.join(str(c) for c in b) for b in coords])
2932
if osrm_base_url is None:
3033
if len(coords) > 100:
31-
print("ERROR: Maximum locations for public OSRM server is 100")
34+
logger.error("Maximum locations for public OSRM server is 100")
3235
return points, cost, duration, tour
3336
url = ('http://router.project-osrm.org/trip/v1/driving/' + a +
3437
'?overview=full')
@@ -49,10 +52,9 @@ def osrm_trip(coords, osrm_base_url=None):
4952
tour.append(w['waypoint_index'])
5053
else:
5154
data = r.json()
52-
print(("OSRM ERROR code={0!s}, message={0!s}"
53-
.format(data['code'], data['message'])))
55+
logger.error(f"OSRM ERROR code={data['code']}, message={data['message']}")
5456
except Exception as e:
55-
print(("ERROR: {0!s}".format(e)))
57+
logger.error(f"ERROR: {e}")
5658
return points, cost, duration, tour
5759

5860

@@ -76,7 +78,7 @@ def main(argv=sys.argv[1:]):
7678

7779
args = parser.parse_args(argv)
7880

79-
print(args)
81+
logger.debug(f"Arguments: {args}")
8082

8183
df = pd.read_csv(args.input)
8284

@@ -101,8 +103,7 @@ def main(argv=sys.argv[1:]):
101103
else:
102104
N = len(coords)
103105

104-
print(('TSP: {:d}, Cost: {:d}, Duration: {:0.1f}, N: {:d}'
105-
.format(l, cost, duration, N)))
106+
logger.info(f'TSP: {l}, Cost: {cost}, Duration: {duration:.1f}, N: {N}')
106107

107108
total_distance += cost
108109
total_duration += duration
@@ -150,14 +151,13 @@ def main(argv=sys.argv[1:]):
150151

151152
fn, fe = os.path.splitext(args.save_map)
152153
fname = "{:s}-{:d}{:s}".format(fn, l, fe)
153-
print(("Save map HTML to file '{:s}'".format(fname)))
154+
logger.debug(f"Saved map HTML to file '{fname}'")
154155
map_osm.save(fname)
155156

156-
print(("Total distance: {0:.1f}, duration: {1:.1f}".format(total_distance,
157-
total_duration)))
157+
logger.info(f"Total distance: {total_distance:.1f}, duration: {total_duration:.1f}")
158158

159159
# save output to file
160-
print(("Save the output file to '{:s}'".format(args.output)))
160+
logger.info(f"Saved output file to '{args.output}'")
161161
odf = pd.DataFrame(output, columns=['worker_id', 'distance', 'duration', 'n',
162162
'path_order'])
163163
odf.to_csv(args.output, index=False)

allocator/tests/test_cluster_kahip.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
def kahip_available():
2121
"""Check if KaHIP dependencies are available"""
2222
try:
23-
import kahipwrapper
23+
import kahipwrapper # noqa: F401
2424
return True
2525
except ImportError:
2626
return False

0 commit comments

Comments
 (0)