-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstable_match.py
66 lines (50 loc) · 1.68 KB
/
stable_match.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
from slot_agent_classes import Slot, Agent
def assign(data, N, K):
"""
Given a dataframe, returns a list of slots' preferences
and list of agent's preferences, prepped for stable matching
"""
Slot.N = Agent.N = N
Agent.K = Slot.K = K
slots = [None] * N
agents = [None] * N
for i in range(N):
slots[i] = Slot()
agents[i] = Agent(data.loc[i, :])
for i in range(N):
agents[i].consolidate_prefs()
agents[i].notify(slots, i)
for i in range(N):
slots[i].consolidate_prefs()
return slots, agents
def stable_matcher(slots, agents, N):
"""
Input: slots with their preferences and agents with their preferences. Matches to be agent-optimal using Gale-Shapley algorithm.
"""
proposals_queue = list(range(N))
slots_queue = set()
while proposals_queue:
# proposal stage
for agent_id in proposals_queue:
slot = agents[agent_id].propose()
slots[slot].receive_offer(agent_id)
slots_queue.add(slot)
proposals_queue = []
# rejection/maybe stage
for s in slots_queue:
slot = slots[s]
for agent in slot.proposals:
if slot.current_match != agent:
proposals_queue.append(agent)
slot.proposals = [slot.current_match]
slots_queue = set()
final_ans = [None] * N
for i in range(N):
final_ans[i] = slots[i].current_match
return final_ans
def match(data, N, K):
"""
To satisfy the matcher interface.
"""
slots, agents = assign(data, N, K)
return stable_matcher(slots, agents, N)