-
Notifications
You must be signed in to change notification settings - Fork 7
/
smartqueue.py
448 lines (364 loc) · 16.8 KB
/
smartqueue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# -*- coding: utf-8 -*-
"""SmartQueue v0.4.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Pvcqcg3XtA_JhshkWWkx_6Bk7RkpKJAW
"""
# advanced date data types
# ! pip install arrow
from random import randrange # to simulate occupancy sensor and queue times
import random # simulate the assignment of addresses
import unittest
import uuid # unique IDs for queues
import arrow # advanced date data types
from enum import Enum # for reservation states
class ReservationState(Enum):
RESERVED = 1
CANCELED = 2
MISSED = 3
COMPLETED = 4
TERMINATED = 5
class Reservation:
def __init__(self, person_id, occupants, reward_points):
self.id = uuid.uuid1()
self.person_id = person_id
self.state = ReservationState.RESERVED
self.reward_points = reward_points
self.occupants = occupants
def update(self, new_state):
self.state = new_state
class QueueStatus(Enum):
ACTIVE = 1
TERMINATED = 2
class ReserveActionResult(Enum):
SUCCESS = 1
DOUBLE_BOOKING_FAILURE = 2
OTHER_FAILURE = 3
class Queue:
def __init__(self, queue_id, max_capacity, open_datetime, close_datetime, address, destination, resource_id):
self.id = queue_id
self.open_datetime = arrow.get(open_datetime)
self.close_datetime = arrow.get(close_datetime)
self.max_capacity = max_capacity
self.address = address
self.destination = destination
self.resource_id = resource_id
self.reservations = []
self.status = QueueStatus.ACTIVE
self.__active_reservation_states = [ReservationState.RESERVED, ReservationState.COMPLETED]
def terminate(self):
for reservation in self.reservations:
if reservation.state in self.__active_reservation_states:
reservation.state = ReservationState.TERMINATED
self.status = QueueStatus.TERMINATED
def __reservation_is_active (self, reservation):
reservation_active = reservation.state in self.__active_reservation_states
return reservation_active
def active_occupants(self):
active_occupants = 0
for reservation in self.reservations:
if (self.__reservation_is_active(reservation)):
active_occupants += reservation.occupants
return active_occupants
def remaining_capacity(self, remaining_resource_capacity, remaining_location_capacity):
remaining_queue_capacity = self.max_capacity - self.active_occupants()
return min(remaining_location_capacity, remaining_resource_capacity, remaining_queue_capacity)
def reward(self, remaining_resource_capacity, remaining_location_capacity):
remaining_capacity = self.remaining_capacity(remaining_location_capacity, remaining_resource_capacity)
max_capacity = self.max_capacity
return remaining_capacity/max_capacity
def __find_reservation(self, person_id):
reservation_found = None
for reservation in self.reservations:
if (reservation.person_id == person_id):
reservation_found = reservation
return reservation_found
def __remaining_queue_capacity(self):
return self.max_capacity - self.active_occupants()
def reservation(self, person_id):
return self.__find_reservation(person_id)
def reserve(self, person_id, proof_of_purchase, occupants, reward_points, remaining_resource_capacity, remaining_location_capacity):
remaining_capacity = self.remaining_capacity(remaining_location_capacity, remaining_resource_capacity)
capacity_remains = remaining_capacity >= occupants
result_code = ReserveActionResult.OTHER_FAILURE
reservation_is_new = self.__find_reservation(person_id) is None
queue_is_active = self.status == QueueStatus.ACTIVE
if reservation_is_new and capacity_remains and queue_is_active:
res = Reservation(person_id, occupants, reward_points)
self.reservations.append(res)
result_code = ReserveActionResult.SUCCESS
result = {
'code':result_code,
'remaining_resource_capacity':remaining_resource_capacity,
'remaining_queue_capacity':remaining_capacity,
'reward_points':reward_points
}
return result
def __update_reservation (self, reservation, state):
reservation.state = state
def cancel_reservation(self, person_id):
res = self.__find_reservation(person_id)
reservation_found = not (res is None)
if reservation_found:
self.__update_reservation(res, ReservationState.CANCELED)
def complete_reservation(self, person_id):
res = self.__find_reservation(person_id)
reservation_found = not (res is None)
if reservation_found and self.__reservation_is_active(res):
self.__update_reservation(res, ReservationState.COMPLETED)
def miss_reservation(self, person_id):
res = self.__find_reservation(person_id)
reservation_found = not (res is None)
reserved = (res.state == ReservationState.RESERVED)
if reservation_found and reserved:
self.__update_reservation(res, ReservationState.MISSED)
def ranges_overlap(r1_start, r1_end, r2_start, r2_end):
r1_start = arrow.get(r1_start)
r2_start = arrow.get(r2_start)
r1_end = arrow.get(r1_end)
r2_end = arrow.get(r2_end)
starts_overlap = (r1_start >= r2_start) and (r1_start <= r2_end)
ends_overlap = (r1_end >= r2_start) and (r1_end <= r2_end)
r1_is_a_superset = (r1_start <= r2_start) and (r1_end >= r2_end)
ranges_overlap = starts_overlap or ends_overlap or r1_is_a_superset
return ranges_overlap
class Location:
def __init__(self, address, max_capacity):
self.address = address
self.max_capacity = max_capacity
self.queues = []
def add_queue(self, queue):
self.queues.append(queue)
def remaining_capacity(self, start_datetime, end_datetime):
occupants_scheduled_to_be_at_location = 0
for queue in self.queues:
queue_in_range = ranges_overlap(arrow.get(start_datetime), arrow.get(end_datetime), queue.open_datetime, queue.close_datetime)
if queue_in_range:
occupants_scheduled_to_be_at_location += queue.active_occupants()
return self.max_capacity - occupants_scheduled_to_be_at_location
class Resource:
def __init__(self, id, max_occupancy, occupant_sensor):
self.id = id
self.capacity = max_occupancy
self.__occupant_sensor = occupant_sensor
def occupants(self):
return self.__occupant_sensor()
def remaining_capacity(self):
return self.capacity - self.__occupant_sensor()
class SmartQueue:
def __init__(self, queue_schedule):
self.__resources = []
self.__locations = []
self.__queues = []
self.update(queue_schedule)
def debug_locations(self):
return self.__locations
def debug_resources(self):
return self.__resources
def debug_queues(self):
return self.__queues
def __resource_does_not_exist(self, resource_id):
exists = False
for resource in self.__resources:
if resource.id == resource_id: exists = True
return not exists
def __location_does_not_exist(self, address):
exists = False
for location in self.__locations:
if location.address.lower() == address.lower(): exists = True
return not exists
def __queue_does_not_exist(self, queue_id):
exists = False
for queue in self.__queues:
if queue.id == queue_id: exists = True
return not exists
def __add_resource_if_it_does_not_exist(self, resource_id, resource):
if self.__resource_does_not_exist(resource_id):
self.__resources.append(resource)
def __add_location_if_it_does_not_exist(self, address, location):
if self.__location_does_not_exist(address):
self.__locations.append(location)
def __add_queue_if_it_does_not_exist(self, queue_id, queue, address):
if self.__queue_does_not_exist(queue_id):
self.__queues.append(queue)
#add the new queue to the proper location
location = self.__find_location(address)
location.add_queue(queue)
def update(self, queue_schedule):
#update resources
for resource in queue_schedule:
resource_id = resource['resource_id']
max_occupancy = resource['max_occupancy']
occupant_sensor = dummy_sensor #resource['occupancy_sensor']
new_resource = Resource(resource_id, max_occupancy, occupant_sensor)
self.__add_resource_if_it_does_not_exist(resource_id, new_resource)
#update locations
for location in resource['locations']:
address = location['address']
max_capacity = location['max_capacity']
new_location = Location(address, max_capacity)
self.__add_location_if_it_does_not_exist(address, new_location)
#update queues
for queue in location['queues']:
queue_id = queue['queue_id']
max_capacity = queue['max_capacity']
start_datetime = queue['start_datetime']
end_datetime = queue['end_datetime']
address = queue['address']
destination = queue['destination']
new_queue = Queue(queue_id, max_capacity, start_datetime, end_datetime, address, destination, resource_id)
self.__add_queue_if_it_does_not_exist(queue_id, new_queue, address)
def __find_location(self, address):
for location in self.__locations:
if location.address.lower() == address.lower():
return location
def __find_resource(self, resource_id):
for resource in self.__resources:
if resource.id == resource_id:
return resource
@staticmethod
def __queue_option(queue, reward, resource):
option = {
'queue_id':queue.id,
'start_time':queue.open_datetime,
'end_time':queue.close_datetime,
'resource_id':queue.resource_id,
'address':queue.address,
'destination':queue.destination,
'reward': reward,
'queue_percentage': queue.active_occupants()/queue.max_capacity,
'train_percentage': resource.occupants()/resource.capacity,
'max_capacity':queue.max_capacity
}
return option
def list_queue_options(self, resource_id, address, destination, start_datetime, end_datetime):
options = []
for queue in self.__queues:
#determine if the queue matches criteria
# resource_matches = (queue.resource_id == resource_id)
location_matches = (queue.address.lower() == address.lower())
destination_matches = (queue.destination.lower() == destination.lower())
time_matches = ranges_overlap(start_datetime, end_datetime, queue.open_datetime, queue.close_datetime)
queue_matches = location_matches and destination_matches and time_matches
#determine if the queue has capacity
resource = self.__find_resource(queue.resource_id)
remaining_resource_capacity = resource.remaining_capacity()
location = self.__find_location(queue.address)
remaining_location_capacity = location.remaining_capacity(start_datetime, end_datetime)
remaining_queue_capacity = queue.remaining_capacity(remaining_resource_capacity, remaining_location_capacity)
queue_has_capacity = remaining_queue_capacity > 0
str_remaining_resource_capacity = str(remaining_resource_capacity)
str_remaining_location_capacity = str(remaining_location_capacity)
str_remaining_queue_capacity = str(remaining_queue_capacity)
queue_has_capacity = remaining_queue_capacity > 0
if (queue_matches and queue_has_capacity):
resource = self.__find_resource(queue.resource_id)
remaining_resource_capacity = resource.remaining_capacity()
location = self.__find_location(address)
remaining_location_capacity = location.remaining_capacity(start_datetime, end_datetime)
reward_points = queue.reward(remaining_resource_capacity, remaining_location_capacity)
options.append(self.__queue_option(queue, reward_points, resource))
return options
def __find_queue(self, queue_id):
for queue in self.__queues:
if queue.id == queue_id:
return queue
def reserve(self, person_id, proof_of_purchase, occupants, queue_id):
#TODO: check for overlapping reservations
queue = self.__find_queue(queue_id)
resource = self.__find_resource(queue.resource_id)
remaining_resource_capacity = resource.remaining_capacity()
location = self.__find_location(queue.address)
remaining_location_capacity = location.remaining_capacity(queue.open_datetime, queue.close_datetime)
reward_points = queue.reward(remaining_resource_capacity, remaining_location_capacity)
result = queue.reserve(person_id, proof_of_purchase, occupants, reward_points, remaining_resource_capacity, remaining_location_capacity)
return result
@staticmethod
def __reservation_details(reservation, queue, resource):
details = {
'reservation_id':reservation.id,
'reservation_state':reservation.state,
'queue_id':queue.id,
'start_time':queue.open_datetime,
'end_time':queue.close_datetime,
'resource':queue.resource_id,
'address':queue.address,
'destination':queue.destination,
'reward_points':reservation.reward_points,
'queue_percentage': queue.active_occupants()/queue.max_capacity,
'train_percentage': resource.occupants()/resource.capacity
}
return details
def list_reservations(self, person_id):
reservations = []
for queue in self.__queues:
for reservation in queue.reservations:
if reservation.person_id == person_id:
resource = self.__find_resource(queue.resource_id)
details = self.__reservation_details(reservation, queue, resource)
reservations.append(details)
return reservations
def complete_reservation(self, queue_id, person_id):
queue = self.__find_queue(queue_id)
queue.complete_reservation(person_id)
def cancel_reservation(self, queue_id, person_id):
queue = self.__find_queue(queue_id)
queue.cancel_reservation(person_id)
def miss_reservation(self, queue_id, person_id):
queue = self.__find_queue(queue_id)
queue.miss_reservation(person_id)
def terminate_queues_for_a_location_and_timeframe(self, address, start_datetime, end_datetime):
pass
def terminate_queues_for_a_resource_and_timeframe(self, resource_id):
pass
def archive_expired_data(self):
#TODO:remove exprired queuees
#TODO:remove unused resources
#TODO:remove unused locations
pass
#needed to test the smart queue
def dummy_sensor():
return 0
testqueue= [
{'resource_id':'resource1',
'max_occupancy':5,
'occupancy_sensor':dummy_sensor,
'locations':[{'address':'address1',
'max_capacity':3,
'queues':[{'queue_id':'queue1',
'start_datetime':arrow.get('2020-07-06 13:00', 'YYYY-MM-DD HH:mm'),
'end_datetime':arrow.get('2020-07-06 13:10', 'YYYY-MM-DD HH:mm'),
'max_capacity':6,
'address':'address1',
'destination':'destination1',
'resource_id':'resource1'}
]
}
]
},
{'resource_id':'resource2',
'max_occupancy':4,
'occupancy_sensor':dummy_sensor,
'locations':[{'address':'address2',
'max_capacity':5,
'queues':[{'queue_id':'queue2',
'start_datetime':arrow.get('2020-07-06 13:00', 'YYYY-MM-DD HH:mm'),
'end_datetime':arrow.get('2020-07-06 13:10', 'YYYY-MM-DD HH:mm'),
'max_capacity':2,
'address':'address2',
'destination':'destination1',
'resource_id':'resource2'},
{'queue_id':'queue3',
'start_datetime':arrow.get('2020-07-06 13:10', 'YYYY-MM-DD HH:mm'),
'end_datetime':arrow.get('2020-07-06 13:20', 'YYYY-MM-DD HH:mm'),
'max_capacity':3,
'address':'address2',
'destination':'destination1',
'resource_id':'resource2'}
]
}
]
}
]
#Initialize SmartQueue with dummy data for fast startup of the application.
sq = SmartQueue(testqueue)