-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGeocrowd.py
707 lines (608 loc) · 28.5 KB
/
Geocrowd.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
import csv
import copy
import random
import Utils
import networkx as nx
import numpy as np
from collections import defaultdict, Counter
from Params import Params
reachable_range = Utils.reachable_distance()
def flowDict2Matches(flowDict):
"""
Create a list of worker-task matches from flow_dict
:param flowDict:
:return:
"""
matches = []
for wid in flowDict.keys():
if wid != "s":
for tid in flowDict[wid].keys():
if tid != "d":
if flowDict[wid][tid] == 1:
matches.append((tid, wid))
return matches
"""
Counting the number of satisfiable matches, which have worker-task distance smaller than a reachable distance
"""
def satisfiableMatches(matches, wLoc, tLoc, reachable_distance_map):
c = defaultdict(list)
count = 0
total_travel_dist = 0.0
for tid, wid in matches:
c[wid].append(tid)
for wid, taskSet in c.items():
for tid in taskSet:
# any satisfiable worker-task --> break
dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[wid][0], wLoc[wid][1])
if dist <= reachable_distance_map[wid]:
count += 1
total_travel_dist += dist
break
return count, total_travel_dist/count
def perturbedData(wtList, p, dp):
"""
Add noise to worker or task list
:param wtList: worker or task list [(lat, lon, id), ...]
:param p: parameters
:param dp: differential privacy object
:return: perturbed list
"""
perturbedList = []
u = Utils.distance(p.x_min, p.y_min, p.x_max, p.y_min) / Params.GEOI_GRID_SIZE
v = Utils.distance(p.x_min, p.y_min, p.x_min, p.y_max) / Params.GEOI_GRID_SIZE
rad = Utils.euclidean_2_radian((u, v))
cell_size = np.array([rad[0], rad[1]])
for lat, lon, id in wtList:
noisyLat, noisyLon = dp.addPolarNoise(p.eps, p.radius, (lat, lon)) # perturbed noisy location
roundedLoc = Utils.round_2_grid((noisyLat, noisyLon), cell_size, p.x_min, p.y_min) # rounded to grid
perturbedList.append([roundedLoc[0], roundedLoc[1], id])
return perturbedList
# DG = nx.DiGraph()
# for tuple in [("s",0,2), ("s",1,9), (0,1,1), (1,0,2), (0,3,5), (1,3,4)]:
# print (DG.out_degree(2,weight='weight'))
# print (DG.successors(2))
# print (DG.neighbors(0))
# print(nx.maximum_flow_value(DG, "s", 3))
def createDG(workers, taskids, b=1):
"""
Create directed graph between worker nodes and task nodes
:param workers:
:param taskids:
:param b:
:return:
"""
DG = nx.DiGraph()
# create edges from source to workers' nodes
for wid in workers.keys():
DG.add_edge("s", wid, capacity=b)
# create edges from tasks' nodes to destination
for tid in taskids:
DG.add_edge(tid, "d", capacity=1)
# create edges between workers and tasks
for wid, taskSet in workers.items():
for tid in taskSet:
DG.add_edge(wid, tid, capacity=1)
return DG
"""
Compute max-flow from dict
"""
def maxFlowValue(workers, taskids, b=1):
"""
Compute max-flow between source s and destination d
:param workers:
:param taskids:
:param b:
:return:
"""
DG = createDG(workers, taskids, b)
return nx.maximum_flow_value(DG, "s", "d")
"""
Compute max-flow from dict
"""
def maxFlow(workers, taskids, b=1):
"""
Compute max-flow between source s and destination d
:param workers:
:param taskids:
:param b:
:return:
"""
DG = createDG(workers, taskids, b)
return nx.maximum_flow(DG, "s", "d")
"""
Sample workers and tasks data
"""
def sampleWorkersTasks(workerFile, taskFile, wCount, tCount):
"""
:param workerFile:
:param taskFile:
:param wCount: worker count
:param tCount: task count
:return: worker list: [(lat, lon, id), ...] and task list [(lat, lon, id), ...]
"""
wList, taskList = [], []
wLoc, tLoc = {}, {}
w, t = 0, 0
with open(workerFile) as worker_file:
reader = csv.reader(worker_file, delimiter=',')
for row in reader:
lat, lon, wid = float(row[0]), float(row[1]), int(row[2])
wList.append((lat, lon, wid)) # lat, lon, id
wLoc[wid] = (lat, lon)
w += 1
if w == wCount:
break
with open(taskFile) as task_file:
reader = csv.reader(task_file, delimiter=',')
for row in reader:
lat, lon, tid = float(row[0]), float(row[1]), t
taskList.append((lat, lon, tid)) # lat, lon, id (use counter as taskid)
tLoc[tid] = (lat, lon)
t += 1
if t == tCount:
break
worker_file.close()
task_file.close()
return wList, taskList, wLoc, tLoc
# print (sampleWorkersTasks("./dataset/tdrive/vehicles.txt", "./dataset/tdrive/passengers.txt", 10, 5))
"""
Crete bipartite graph from workers and tasks list
"""
def createBipartiteGraph(wList, tList, reachable_distance_map):
"""
:param wList: array of workers
:param tList: array of tasks
:param reachableDist: in meters
:return:
"""
workers = defaultdict(set)
"""
for each worker, find a set of reachable tasks
"""
for wlat, wlon, wid in wList:
for tlat, tlon, tid in tList:
noisy_dist = Utils.distance(wlat, wlon, tlat, tlon)
reachable_distance = reachable_distance_map[wid]
if noisy_dist <= reachable_distance:
workers[tid].add(wid)
return workers
def createBipartiteGraphU2U(wList, tList, reachable_distance_map, reachable_prob_U2U, p):
"""
:param wList: array of workers
:param tList: array of tasks
:param reachableDist: in meters
:return:
"""
workers = defaultdict(set)
"""
for each worker, find a set of reachable tasks
"""
for wlat, wlon, wid in wList:
for tlat, tlon, tid in tList:
reachable_distance = reachable_distance_map[wid]
noisy_dististance = Utils.distance(wlat, wlon, tlat, tlon)
reachable_prob = reachable_prob_U2U[
str(Utils.round_reachable_dist(reachable_distance)) + ":" +
str(Utils.dist_range(noisy_dististance, Params.STEP))
]
# reachability >= a threshold
if reachable_prob >= p.reachabilityThresholdU2U:
workers[tid].add(wid)
return workers
# wList, tList = sampleWorkersTasks("./dataset/tdrive/vehicles.txt", "./dataset/tdrive/passengers.txt", 1000, 1000)
# print (createBipartiteGraph(wList, tList, 1000))
"""
Implementation of Ranking algorithm for online bipartite matching.
Citation: Karp et al. An Optimal Algorithm for On-line Bipartite Matching
Ranking based on random rank.
"""
def rankingRandom(candidateWorkers, taskids, wLoc, tLoc, reachable_distance_map):
"""
:param candidateWorkers: map each workerid to a list of nearby tasks
:param taskids: list of taskids arriving in order
:return: a list matching pairs
"""
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# random permutation of workers' ranks
randomRanks = list(range(len(workers)))
random.shuffle(randomRanks)
workerRank = dict([(wid, randomRanks[i]) for i, wid in enumerate(workers.keys())])
total_notified_workers = 0
total_travel_dist = 0.0
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
if len(eligibleWids) > 0:
# find the worker of highest rank
highestRankWid = min(eligibleWids, key=lambda w:workerRank[w])
total_notified_workers += 1
actual_dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0],
wLoc[highestRankWid][1])
if actual_dist <= reachable_distance_map[highestRankWid]:
matches.append((tid, highestRankWid))
total_travel_dist += actual_dist
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
# delete from workerRank & tasks
# del workerRank[highestRankWid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist / matched_count
return matched_count, false_hits, average_travel_dist, total_notified_workers
"""
Similar to above function but ranking based on distance.
"""
def rankingNearest(candidateWorkers, taskids, wLoc, tLoc, reachable_distance_map):
"""
:param candidateWorkers: map each workerid to a list of nearby tasks
:param taskids: list of taskids arriving in order
:return: a list matching pairs
"""
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
total_notified_workers = 0
total_travel_dist = 0.0
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
if len(eligibleWids) > 0:
# find the worker of highest rank
highestRankWid = min(eligibleWids, key=lambda w:Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[w][0], wLoc[w][1]))
total_notified_workers += 1
actual_dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0],
wLoc[highestRankWid][1])
if actual_dist <= reachable_distance_map[highestRankWid]:
matches.append((tid, highestRankWid))
total_travel_dist += actual_dist
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
# delete from workerRank & tasks
# del workerRank[highestRankWid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist / matched_count
return matched_count, false_hits, average_travel_dist, total_notified_workers
# workers = {0:set([1,2]), 2:set([0,3]), 3:set([2]), 4:set([2,3]), 5:set([5])}
# taskids = [0,1,2,3,4,5]
# print (rankingAlgo(workers, taskids))
"""
Modify ranking algorithm such that each worker is selected by the highest reachability probability rather than
the highest random rank. This technique not only increases the number of performed tasks but also reduces the
travel distance.
"""
def rankingByReachability(candidateWorkers, taskids, wLoc, tLoc, reachable_prob_U2E, reachable_distance_map):
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workers
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
if len(eligibleWids) > 0:
# find the worker of highest probability of reachability
highestRankWid = max(eligibleWids, key=lambda wid:reachable_prob_U2E[
str(Utils.round_reachable_dist(reachable_distance_map[wid])) + ":" +
str(Utils.dist_range(Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[wid][0], wLoc[wid][1]), Params.STEP))
])
matches.append((tid, highestRankWid))
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
return matches
"""
Modify ranking algorithm such that in each iteration task is sent to a matched worker,
the worker responses to the requester if the task is reachable. Otherwise, the task will be sent
to the next matched worker. This stragegy helps to increase the number of performed tasks.
Note: We assume that workers would accept their matched tasks as long as the tasks are reachable.
"""
def rankingResendRandom(candidateWorkers, taskids, wLoc, tLoc, reachable_distance_map):
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# random permutation of workers' ranks
randomRanks = list(range(len(workers)))
random.shuffle(randomRanks)
workerRank = dict([(wid, randomRanks[i]) for i, wid in enumerate(workers.keys())])
# total disclosure
total_notified_workers = 0
total_travel_dist = 0.0
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
matched = False # if matched is True, go to the next task
while len(eligibleWids) > 0 and not matched:
# find the worker of the highest rank.
highestRankWid = max(eligibleWids, key=lambda x:workerRank[x])
actual_dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0], wLoc[highestRankWid][1])
total_notified_workers += 1
if actual_dist <= reachable_distance_map[highestRankWid]: # satisfiable match
matches.append((tid, highestRankWid))
total_travel_dist += actual_dist
matched = True
else:
eligibleWids.remove(highestRankWid)
if matched:
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist/matched_count if matched_count != 0 else 0
return matched_count, false_hits, average_travel_dist, total_notified_workers
"""
Similar to above function except ranking by distance.
"""
def rankingResendNearest(candidateWorkers, taskids, wLoc, tLoc, reachable_distance_map):
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# total disclosure
total_notified_workers = 0
total_travel_dist = 0.0
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
matched = False # if matched is True, go to the next task
while len(eligibleWids) > 0 and not matched:
# find the worker of the highest rank.
highestRankWid = min(eligibleWids, key=lambda x:Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[x][0], wLoc[x][1]))
actual_dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0], wLoc[highestRankWid][1])
total_notified_workers += 1
if actual_dist <= reachable_distance_map[highestRankWid]: # satisfiable match
matches.append((tid, highestRankWid))
total_travel_dist += actual_dist
matched = True
else:
eligibleWids.remove(highestRankWid)
if matched:
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist/matched_count if matched_count != 0 else 0
return matched_count, false_hits, average_travel_dist, total_notified_workers
"""
Modify ranking algorithm that considers both reachability probability and resend strategy.
"""
def rankingByReachabilityResend(candidateWorkers, taskids, wLoc, tLoc, reachable_prob_U2E, reachable_distance_map):
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# total disclosure
total_notified_workers = 0
total_travel_dist = 0.0
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
matched = False # if matched is True, go to the next task
while len(eligibleWids) > 0 and not matched:
# find the worker of highest probability of reachability
highestRankWid = max(eligibleWids, key=lambda wid:reachable_prob_U2E[
str(Utils.round_reachable_dist(reachable_distance_map[wid])) + ":" +
str(Utils.dist_range(Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[wid][0], wLoc[wid][1]), Params.STEP))
])
dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0], wLoc[highestRankWid][1])
total_notified_workers += 1
if dist <= reachable_distance_map[highestRankWid]: # satisfiable match
matches.append((tid, highestRankWid))
total_travel_dist += dist
matched = True
else:
eligibleWids.remove(highestRankWid)
if matched:
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist/matched_count if matched_count != 0 else 0
return matched_count, false_hits, average_travel_dist
"""
Modify ranking algorithm that considers reachability probability, resend strategy and worker's acceptance policy.
The policy is that a worker can reject a task without knowing the task location. This helps to decrease the amount
of extra disclosure.
"""
def rankingByReachabilityEmpirical(candidate_workers, taskids, wLoc, tLoc, reachable_prob_U2E, reachable_distance_map, reachability_threshold):
matches = []
tasks = copy.deepcopy(candidate_workers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# total disclosure
total_notified_workers = 0
total_travel_dist = 0.0
# false dismissals/false hits during U2E
# false_hits equals to total_notified_workers - number of matches
false_dismissals = 0 # dismiss a reachable worker.
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
matched = False # if matched is True, go to the next task
rejected = False # if rejected is True, go to the next task
while len(eligibleWids) > 0 and not matched and not rejected:
# find the worker of highest probability of reachability (U2E)
highestRankWid = max(eligibleWids, key=lambda wid:reachable_prob_U2E[
str(Utils.round_reachable_dist(reachable_distance_map[wid])) + ":" +
str(Utils.dist_range(Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[wid][0], wLoc[wid][1]),
Params.STEP))
])
# worker compute the actual distance and reachablility probability
actual_dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0], wLoc[highestRankWid][1])
highest_reachable_prob = reachable_prob_U2E[
str(Utils.round_reachable_dist(reachable_distance_map[highestRankWid])) + ":" +
str(Utils.dist_range(actual_dist, Params.STEP))] # U2E.
if highest_reachable_prob < reachability_threshold:
rejected = True
if actual_dist <= reachable_distance_map[highestRankWid]: # if this worker is reachable.
false_dismissals += 1
continue
total_notified_workers += 1
if actual_dist <= reachable_distance_map[highestRankWid]: # satisfiable match
matched = True
matches.append((tid, highestRankWid))
total_travel_dist += actual_dist
else:
eligibleWids.remove(highestRankWid)
if matched:
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist/matched_count if matched_count != 0 else 0
return matched_count, false_hits, average_travel_dist, false_dismissals, total_notified_workers
"""
Similar to above function except using analytical results.
"""
def rankingByReachabilityAnalytical(candidateWorkers, taskids, wLoc, tLoc, reachable_distance_map, reachability_threshold_U2E, p):
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# total disclosure
total_notified_workers = 0
total_travel_dist = 0.0
# false dismissals/false hits during U2E
# false_hits equals to total_notified_workers - number of matches
false_dismissals = 0 # dismiss a reachable worker.
for tid in taskids: # iterate through task list
if tid in tasks: # check if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
matched = False # if matched is True, go to the next task
rejected = False # if rejected is True, go to the next task
while len(eligibleWids) > 0 and not matched and not rejected:
# requester finds the worker of highest probability of reachability (U2E)
highestRankWid = max(eligibleWids, key=lambda wid:Utils.reachable_prob_U2E(
reachable_distance_map[wid],
Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[wid][0], wLoc[wid][1]),
p.eps, p.radius))
# worker compute the actual distance and reachablility probability
actual_dist = Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0], wLoc[highestRankWid][1])
highest_reachable_prob = Utils.reachable_prob_U2E(
reachable_distance_map[highestRankWid],
Utils.distance(tLoc[tid][0], tLoc[tid][1], wLoc[highestRankWid][0], wLoc[highestRankWid][1]),
p.eps, p.radius) # U2E.
if highest_reachable_prob < reachability_threshold_U2E:
rejected = True
if actual_dist <= reachable_distance_map[highestRankWid]: # if this worker is reachable.
false_dismissals += 1
continue
total_notified_workers += 1
if actual_dist <= reachable_distance_map[highestRankWid]: # satisfiable match
matched = True
matches.append((tid, highestRankWid))
total_travel_dist += actual_dist
else:
eligibleWids.remove(highestRankWid)
if matched:
# affected tasks
affectedTids = workers[highestRankWid]
# delete highestRankWid from workers, tid from tasks
del workers[highestRankWid]
del tasks[tid]
for _tid in affectedTids:
if _tid != tid:
tasks[_tid].discard(highestRankWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
matched_count = len(matches)
false_hits = total_notified_workers - matched_count
average_travel_dist = total_travel_dist/matched_count if matched_count != 0 else 0
return matched_count, false_hits, average_travel_dist, false_dismissals, total_notified_workers
"""
Implementation of balance algorithm for online b-matching.
Citation: Kalyanasundaram and Kruhs. An optimal deterministic algorithm for online b-matching
"""
def balance(candidateWorkers, taskids, b):
"""
:param candidateWorkers: map each workerid to a list of nearby tasks
:param taskids: list of taskids arriving in order
:param b: at most b tasks can be matched to one worker
:return: a list matching pairs
"""
matches = []
tasks = copy.deepcopy(candidateWorkers)
workers = Utils.worker_dict_2_task_dict(tasks) # create dict with key = workerid
# initialize maximum number of tasks matched to each worker
workerCapacity = Counter(dict([(wid, b) for wid in workers.keys()]))
for tid in taskids: # iterate through task list
if tid in tasks: # if tid has eligible nearby workers
eligibleWids = list(tasks[tid])
if len(eligibleWids) > 0:
# find the worker of highest remaining capacity
maxCapacityWid = max(eligibleWids, key=lambda x:workerCapacity[x])
matches.append((tid, maxCapacityWid))
# matches += 1
affectedTids = workers[maxCapacityWid] # affected tasks
del tasks[tid] # remove tid from tasks
# update workerCapacity and workers
workerCapacity[maxCapacityWid] -= 1
if workerCapacity[maxCapacityWid] == 0: # disable this worker
del workerCapacity[maxCapacityWid]
del workers[maxCapacityWid]
else:
workers[maxCapacityWid].discard(tid)
if len(workers[maxCapacityWid]) == 0:
del workers[maxCapacityWid]
del workerCapacity[maxCapacityWid]
for _tid in affectedTids:
# remove from tasks
if _tid != tid and maxCapacityWid not in workerCapacity:
tasks[_tid].discard(maxCapacityWid)
if len(tasks[_tid]) == 0:
del tasks[_tid]
return matches
# workers = {0:set([1,2,6]), 2:set([0,3]), 3:set([2]), 4:set([2,3]), 5:set([5])}
# taskids = [0,1,2,3,4,5,6]
# print (balanceAlgo(workers, taskids, 1))