Skip to content

Commit

Permalink
minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Leot6 committed Apr 29, 2021
1 parent ded5e10 commit 9dc4d2a
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 124 deletions.
18 changes: 9 additions & 9 deletions lib/analysis/animation_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

veh_showing_route_step = 1
amin_frame_interval = 75

dpi = 100

# animation
def anim(frames_vehs):
Expand Down Expand Up @@ -50,7 +50,7 @@ def animate(n):
fig = plt.figure(figsize=(MAP_WIDTH, MAP_HEIGHT))
plt.xlim((Olng, Dlng))
plt.ylim((Olat, Dlat))
img = mpimg.imread(f'{root_path}/map.png')
img = mpimg.imread(f'{root_path}/map.jpg')
plt.imshow(img, extent=[Olng, Dlng, Olat, Dlat], aspect=(Dlng - Olng) / (Dlat - Olat) * MAP_HEIGHT / MAP_WIDTH)
fig.subplots_adjust(left=0.00, bottom=0.00, right=1.00, top=1.00)
vehs = []
Expand All @@ -65,7 +65,7 @@ def animate(n):
# print('objective', objective, 'num of frames', len(frames_vehs))
print('saving animation....')
start_time = time.time()
anime.save(f'{root_path}/output-gitignore/anim_new.mp4', dpi=200, fps=None, extra_args=['-vcodec', 'libx264'])
anime.save(f'{root_path}/output-gitignore/anim_new.mp4', dpi=dpi, fps=None, extra_args=['-vcodec', 'libx264'])
print('...running time of encoding video : %.05f seconds' % (time.time() - start_time))
return anime

Expand Down Expand Up @@ -141,7 +141,7 @@ def animate(n):
fig = plt.figure(figsize=(MAP_WIDTH, MAP_HEIGHT))
plt.xlim((Olng, Dlng))
plt.ylim((Olat, Dlat))
img = mpimg.imread(f'{root_path}/map.png')
img = mpimg.imread(f'{root_path}/map.jpg')
plt.imshow(img, extent=[Olng, Dlng, Olat, Dlat], aspect=(Dlng - Olng) / (Dlat - Olat) * MAP_HEIGHT / MAP_WIDTH)
fig.subplots_adjust(left=0.00, bottom=0.00, right=1.00, top=1.00)
vehs = []
Expand Down Expand Up @@ -173,7 +173,7 @@ def animate(n):
print('objective', objective, 'num of frames', len(frames_vehs))
print('saving animation....')
start_time = time.time()
anime.save(f'{root_path}/output-gitignore/anim_{objective}.mp4', dpi=200, fps=None, extra_args=['-vcodec', 'libx264'])
anime.save(f'{root_path}/output-gitignore/anim_{objective}.mp4', dpi=dpi, fps=None, extra_args=['-vcodec', 'libx264'])
print('...running time of encoding video : %.05f seconds' % (time.time() - start_time))
return anime

Expand Down Expand Up @@ -244,7 +244,7 @@ def animate(n):
fig = plt.figure(figsize=(MAP_WIDTH, MAP_HEIGHT))
plt.xlim((Olng, Dlng))
plt.ylim((Olat, Dlat))
img = mpimg.imread(f'{root_path}/map.png')
img = mpimg.imread(f'{root_path}/map.jpg')
plt.imshow(img, extent=[Olng, Dlng, Olat, Dlat], aspect=(Dlng - Olng) / (Dlat - Olat) * MAP_HEIGHT / MAP_WIDTH)
fig.subplots_adjust(left=0.00, bottom=0.00, right=1.00, top=1.00)
vehs = []
Expand Down Expand Up @@ -274,7 +274,7 @@ def animate(n):
print('Dispatcher', dispatcher, 'num of frames', len(frames_vehs))
print('saving animation....')
start_time = time.time()
anime.save(f'{root_path}/output-gitignore/anim_{dispatcher}.mp4', dpi=200, fps=None, extra_args=['-vcodec', 'libx264'])
anime.save(f'{root_path}/output-gitignore/anim_{dispatcher}.mp4', dpi=dpi, fps=None, extra_args=['-vcodec', 'libx264'])
print('...running time of encoding video : %.05f seconds' % (time.time() - start_time))
return anime

Expand Down Expand Up @@ -334,7 +334,7 @@ def animate(n):
plt.xlim((Olng, Dlng))
plt.ylim((Olat, Dlat))

img = mpimg.imread(f'{root_path}/map.png')
img = mpimg.imread(f'{root_path}/map.jpg')
plt.imshow(img, extent=[Olng, Dlng, Olat, Dlat], aspect=(Dlng - Olng) / (Dlat - Olat) * MAP_HEIGHT / MAP_WIDTH)
fig.subplots_adjust(left=0.00, bottom=0.00, right=1.00, top=1.00)
[veh_lng, veh_lat] = get_node_geo(veh.nid)
Expand Down Expand Up @@ -367,6 +367,6 @@ def animate(n):
print('saving animation....')
start_time = time.time()
# plt.show()
anime.save(f'{root_path}/output-gitignore/anim_sche{veh.id}_{dispatcher}.mp4', dpi=200, fps=None, extra_args=['-vcodec', 'libx264'])
anime.save(f'{root_path}/output-gitignore/anim_sche{veh.id}_{dispatcher}.mp4', dpi=dpi, fps=None, extra_args=['-vcodec', 'libx264'])
print('...running time of encoding video : %.05f seconds' % (time.time() - start_time))
return anime
6 changes: 4 additions & 2 deletions lib/dispatcher/osp/osp_assign.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@


def ILP_assign(veh_trip_edges, reqs_pool, reqs_all, reqs_picking=[], prev_assigned_edges=[]):
aa = time.time()
t = time.time()
assert isinstance(reqs_pool, list)
veh_trip_edges = sorted(veh_trip_edges, key=lambda e: (e[0].id, -len(e[1]), e[3]))
prev_vid_Tid_edges = [(veh.id, [r.id for r in trip]) for (veh, trip, sche, cost) in prev_assigned_edges]
Expand Down Expand Up @@ -191,11 +191,13 @@ def ILP_assign(veh_trip_edges, reqs_pool, reqs_all, reqs_picking=[], prev_assign
# if not set(rids_picking) <= set(rids_assigned):
# rids_removed_ILP = list(set(rids_picking) - set(rids_assigned))
# print('rids_picking not assigned this time', rids_removed_ILP)
# print(' ILP running time:', round((time.time() - aa), 2))
# print(' ILP running time:', round((time.time() - t), 2))
# print(' num of reqs')
if not ignore_a_bug_temporary:
assert set(rids_picking) <= set(rids_assigned)

if IS_DEBUG:
print(f' +ILP assignment... ({round((time.time() - t), 2)}s)')
return rids_assigned, vids_assigned, sches_assigned


Expand Down
29 changes: 9 additions & 20 deletions lib/dispatcher/osp/osp_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from lib.simulator.config import IS_DEBUG, T_WARM_UP, T_STUDY
from lib.dispatcher.osp.osp_pool import build_vt_table, get_prev_assigned_edges, CUTOFF_VT, FAST_COMPUTE
from lib.dispatcher.osp.osp_assign import ILP_assign
from lib.dispatcher.osp.osp_assign import ILP_assign, greedy_assign
from lib.analysis.dispatcher_analysis import DispatcherAnalysis
from lib.analysis.objective_analysis import ObjectiveAnalysis

Expand All @@ -34,20 +34,22 @@ def __init__(self, amod):
self.analysis = ObjectiveAnalysis()

def dispatch(self, T):
t = time.time()

reqs_new = self.queue
if Reject_Unassigned:
reqs_prev = sorted(self.reqs_picking, key=lambda r: r.id)
else:
reqs_prev = sorted(self.reqs_picking.union(self.reqs_unassigned), key=lambda r: r.id)

if IS_DEBUG:
print(f' -assigning {len(reqs_prev) + len(reqs_new)} reqs to vehs through OSP...')

# compute the ride-sharing assignment
prev_assigned_edges = get_prev_assigned_edges(self.vehs, self.reqs)

osp_time = time.time()
rids_assigned, vids_assigned, sches_assigned, num_edges = \
ridesharing_match_osp(self.vehs, self.reqs, reqs_new, reqs_prev, self.reqs_picking, prev_assigned_edges, T)
osp_run_time = round((time.time() - osp_time), 2)

# if IS_DEBUG and T_WARM_UP < T <= T_WARM_UP + T_STUDY:
# self.analysis.run_comparison_analysis(self.vehs, self.reqs, self.queue, self.reqs_picking,
Expand All @@ -67,6 +69,9 @@ def dispatch(self, T):
for vid, sche in zip(vids_remove_r, sches_remove_r):
self.vehs[vid].build_route(sche, self.reqs, T)

if IS_DEBUG:
print(f' +assigned reqs: {len(rids_assigned)} ({round((time.time() - t), 2)}s)')

return vids_assigned + vids_remove_r

def __str__(self):
Expand All @@ -77,10 +82,8 @@ def __str__(self):

def ridesharing_match_osp(vehs, reqs_all, reqs_new, reqs_prev, reqs_picking, prev_assigned_edges, T):
# build VT-table
if IS_DEBUG:
print(' -T = %d, building VT-table ...' % T)
a1 = time.time()
veh_trip_edges = build_vt_table(vehs, reqs_new, reqs_prev, T)
veh_trip_edges = sorted(veh_trip_edges, key=lambda e: (e[0].id, -len(e[1]), e[3]))
num_edges = len(veh_trip_edges)

vid_Tid_edges = [(veh.id, [r.id for r in trip]) for (veh, trip, sche, cost) in veh_trip_edges]
Expand All @@ -90,29 +93,17 @@ def ridesharing_match_osp(vehs, reqs_all, reqs_new, reqs_prev, reqs_picking, pre
missed_prev_assigned_edges.append((veh, trip, sche, cost))
veh_trip_edges.extend(missed_prev_assigned_edges)

if IS_DEBUG:
print(' a1 running time:', round((time.time() - a1), 2))

# ILP assign shared trips using VT-table
if IS_DEBUG:
print(' -T = %d, start ILP assign with %d edges...' % (T, len(veh_trip_edges)))
a2 = time.time()
reqs_pool = reqs_prev + reqs_new
ensure_picking_list = reqs_picking if Ensure_Picking else []
rids_assigned, vids_assigned, sches_assigned = \
ILP_assign(veh_trip_edges, reqs_pool, reqs_all, ensure_picking_list, prev_assigned_edges)

if IS_DEBUG:
print(' a2 running time:', round((time.time() - a2), 2))

return rids_assigned, vids_assigned, sches_assigned, num_edges


# find vehicles with schedule changed
def find_changed_trips(vehs, vids_assigned_in_ILP, T):
if IS_DEBUG:
print(' -T = %d, find vehicles with removed requests ...' % T)
a3 = time.time()
vids_remove_r = []
sches_remove_r = []
for veh in vehs:
Expand All @@ -123,8 +114,6 @@ def find_changed_trips(vehs, vids_assigned_in_ILP, T):
new_sche.append((rid, pod, tnid, ddl))
vids_remove_r.append(veh.id)
sches_remove_r.append(copy.deepcopy(new_sche))
if IS_DEBUG:
print(' a3 running time:', round((time.time() - a3), 2))
return vids_remove_r, sches_remove_r


77 changes: 12 additions & 65 deletions lib/dispatcher/osp/osp_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from tqdm import tqdm
from itertools import permutations

from lib.simulator.config import FLEET_SIZE, RIDESHARING_SIZE
from lib.simulator.config import FLEET_SIZE, RIDESHARING_SIZE, IS_DEBUG
from lib.routing.routing_server import get_duration_from_origin_to_dest
from lib.dispatcher.osp.osp_schedule import compute_schedule, test_constraints_get_cost, compute_sche_time

Expand Down Expand Up @@ -38,6 +38,9 @@

# build VT table for each veh, respectively
def build_vt_table(vehs, reqs_new, reqs_prev, T, Re_Optimization=True):
if IS_DEBUG:
t = time.time()

if FAST_COMPUTE:
reqs_pool_vt = reqs_new
rids_prev = {req.id for req in reqs_prev}
Expand All @@ -58,33 +61,8 @@ def build_vt_table(vehs, reqs_new, reqs_prev, T, Re_Optimization=True):
veh_trip_edges.append((veh, trip, best_sche, cost))
# veh.candidate_sches.append(best_sche)

# # debug
# if 60 * (30 + 0) < T <= 60 * (30 + 30):
# global num_of_new_reqs
# global num_of_all_reqs
# num_of_new_reqs.append(len(reqs_new))
# num_of_all_reqs.append(len(reqs_new) + len(reqs_prev))
# print(f'reqs:{round(np.mean(num_of_new_reqs))}/{round(np.mean(num_of_all_reqs))}')
#
# n_largest = 0
# vid_largest = 0
# for veh in vehs:
# veh_vt_1 = VT_TABLE[veh.id][0]
# n = len(veh_vt_1)
# if n > n_largest:
# n_largest = n
# vid_largest = veh.id
# vt_largest = VT_TABLE[vid_largest]
# vt_prev_largest = PREV_VT_TABLE[vid_largest]
# avg_num_of_old_trips = [0] * RIDESHARING_SIZE
# avg_num_of_new_trips = [0] * RIDESHARING_SIZE
# for i in range(0, RIDESHARING_SIZE):
# avg_num_of_old_trips[i] = len(upd_prev_sches(vehs[vid_largest], rids_prev, i+1, T))
# avg_num_of_new_trips[i] = len(vt_largest[i]) - avg_num_of_old_trips[i]
# print('avg_num_of_old_trips', avg_num_of_old_trips)
# print('avg_num_of_new_trips', avg_num_of_new_trips)
# # debug

if IS_DEBUG:
print(f' +computing feasible vehicle trip pairs... ({round((time.time() - t), 2)}s)')
return veh_trip_edges


Expand All @@ -103,14 +81,6 @@ def feasible_shared_trips_search(veh, reqs_new, rids_prev, T, Re_Optimization):
veh_vt[0] = upd_prev_sches(veh, rids_prev, 1, T)
n_prev_trips_k = len(veh_vt[0]) # number of old trips of size 1

# # add rebalanicng trip (old version rebalancing, not used at now, will delete)
# if veh.rebl:
# sche = []
# for leg in veh.route:
# if leg.rid == veh.rebl_req.id:
# sche.append((leg.rid, leg.pod, leg.tnid, leg.ddl))
# veh_vt[0].append((tuple([veh.rebl_req]), sche, compute_sche_time(veh, sche), [sche]))

# add new trips (size 1)
if Re_Optimization:
sub_sches = restore_basic_sub_sches(veh)
Expand All @@ -136,6 +106,9 @@ def feasible_shared_trips_search(veh, reqs_new, rids_prev, T, Re_Optimization):
{rid for (rid, pod, tnid, ddl) in best_sche} - {-1} - set(veh.onboard_rids)
assert {r.id for r in trip} <= {r.id for r in reqs_new}

# if IS_DEBUG:
# print(f' +computing size 1 trip for Vehicle #{veh.id}... ({len(veh_vt[0])} trips)')

# trips of size k (k >= 2)
for k in range(2, RIDESHARING_SIZE + 1):
start_time = time.time()
Expand Down Expand Up @@ -180,40 +153,11 @@ def feasible_shared_trips_search(veh, reqs_new, rids_prev, T, Re_Optimization):
best_sche1, min_cost1, feasible_sches1, num_of_sche_searched1 \
= compute_schedule(veh_params, sub_sches1, req1_params, T)

# sub_sches2 = veh_vt[k - 2][-i][3]
# req2 = tuple(set(trip_k) - set(trip1))[0]
# req2_params = [req2.id, req2.onid, req2.dnid, req2.Clp, req2.Cld]
# best_sche2, min_cost2, feasible_sches2, num_of_sche_searched2 = compute_schedule(veh_params, sub_sches2,
# req2_params, T)
# if best_sche1 and not min_cost2 == min_cost1:
# print(f'len(feasible_S): {len(feasible_sches1)}/{len(feasible_sches2)}, min_cost: {min_cost1} '
# f'/ {min_cost2}, num_s_c:{num_of_sche_searched1}/{num_of_sche_searched2}')
# print('best_sche1', best_sche1)
# print('best_sche2', best_sche2)

best_sche = best_sche1
min_cost = min_cost1
feasible_sches = feasible_sches1
num_of_sche_searched = num_of_sche_searched1

# req_Ts = sorted([r.Ts for r in trip_k])[-2]
#
# if best_sche and k == 4 and len(set([r.onid for r in trip_k] + [r.dnid for r in trip_k])) == k * 2 \
# and 40 < num_of_sche_searched < 50 and req_Ts > 500 and len(veh.onboard_rids) <= 1:
# best_sche_rtv, min_cost_rtv, num_of_sche_searched_rtv, sches_searched_rtv\
# = compute_sche_rtv(veh_params, sub_sches[0], trip_k, T)
# if not best_sche_rtv:
# continue
# print(f'veh {veh.id}, on_board {veh.onboard_rids}, trip {[r.id for r in trip_k]}, '
# f'num of sches {num_of_sche_searched}/{num_of_sche_searched_rtv}')
# # assert best_sche == best_sche_rtv
# if num_of_sche_searched_rtv < 1300:
# a = anim_sche(copy.deepcopy(veh), trip_k, sches_searched, best_sche, 'osp')
# # b = anim_sche(copy.deepcopy(veh), trip_k, sches_searched_rtv, best_sche, 'rtv')
# data = [veh, trip_k, sches_searched, sches_searched_rtv, best_sche]
# with open(f'anime_sche_data_{veh.id}.pickle', 'wb') as f:
# pickle.dump(data, f)

if show_counting:
# count the number of feasible schedules algorithm considers
k_c = k + len(veh.onboard_rids)
Expand Down Expand Up @@ -245,6 +189,9 @@ def feasible_shared_trips_search(veh, reqs_new, rids_prev, T, Re_Optimization):
# print('veh', veh.id, 'cutoff size', k, 'trip, first search')
break

# if IS_DEBUG:
# print(f' +computing size {k} trip for Vehicle #{veh.id}... ({len(veh_vt[k-1])} trips)')

if len(veh_vt[k - 1]) == 0:
for k1 in range(k, RIDESHARING_SIZE):
veh_vt[k1].clear()
Expand Down
6 changes: 3 additions & 3 deletions lib/dispatcher/sba/single_req_batch_assign.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ def ridesharing_match_sba(vehs, reqs_all, reqs_pool, T):
num_edges = len(veh_req_edges)

# ILP assign
# rids_assigned, vids_assigned, sches_assigned = ILP_assign(veh_req_edges, reqs_pool, reqs_all)
rids_assigned, vids_assigned, sches_assigned = greedy_assign(veh_req_edges)
rids_assigned, vids_assigned, sches_assigned = ILP_assign(veh_req_edges, reqs_pool, reqs_all)
# rids_assigned, vids_assigned, sches_assigned = greedy_assign(veh_req_edges)

if IS_DEBUG:
print(f' +assigned reqs {len(rids_assigned)} ({round((time.time() - t), 2)}s)')
print(f' +assigned reqs: {len(rids_assigned)} ({round((time.time() - t), 2)}s)')

return rids_assigned, vids_assigned, sches_assigned, num_edges

Expand Down
12 changes: 6 additions & 6 deletions lib/simulator/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@

# demand volume (percentage of total), simulation start time and its nickname
DMD_VOL = 1 # <= 1
# DMD_SST = parse(DATE + ' 00:00:00')
DMD_SST = parse(DATE + ' 18:30:00') # peak hour
DMD_SST = parse(DATE + ' 00:00:00')
# DMD_SST = parse(DATE + ' 18:30:00') # peak hour
REQ_INIT_IDX = 0
DMD_STR = 'Manhattan'

Expand All @@ -35,7 +35,7 @@

# fleet size, vehicle capacity and ridesharing size
FLEET_SIZE = 2000 # int(2000 * DMD_VOL)
VEH_CAPACITY = 4
VEH_CAPACITY = 6
RIDESHARING_SIZE = int(VEH_CAPACITY * 1.8)

# maximum wait time window, maximum total delay and maximum in-vehicle detour
Expand All @@ -51,8 +51,8 @@

# dispatching and rebalancing methods
# DISPATCHER = 'GI'
DISPATCHER = 'SBA'
# DISPATCHER = 'OSP'
# DISPATCHER = 'SBA'
DISPATCHER = 'OSP'
# DISPATCHER = 'RTV'

REBALANCER = 'NR'
Expand All @@ -78,7 +78,7 @@
IS_STOCHASTIC_SCHEDULE = False
# IS_STOCHASTIC_ROUTING = True
IS_STOCHASTIC_ROUTING = False
LEVEl_OF_STOCHASTIC = 4
LEVEl_OF_STOCHASTIC = 1

# # parameters for Manhattan map
# map width and height (km)
Expand Down
Loading

0 comments on commit 9dc4d2a

Please sign in to comment.