-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelegateAssign.py
More file actions
210 lines (176 loc) · 9.35 KB
/
DelegateAssign.py
File metadata and controls
210 lines (176 loc) · 9.35 KB
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
import pandas as pd
import numpy as np
import random
from openpyxl.workbook import Workbook
def get_file(filename):
file = pd.read_csv(filename)
return file
def get_arcs(committee_data):
neighbors = get_file('neighbors.csv')
neighbors['neighbors'] = neighbors['neighbors'].astype(str).str.split(',')
same_states = get_file('same_states.csv')
same_states['states'] = same_states['states'].astype(str).str.strip().str.split(',')
combined = neighbors.merge(same_states, left_on='area', right_on='area', how='left')
combined['neighbors'] = combined['neighbors'].apply(lambda x: x if isinstance(x, list) else [])
combined['states'] = combined['states'].apply(lambda x: x if isinstance(x, list) else [])
combined['ineligible'] = combined.apply(lambda row: set(row['neighbors'] + row['states']), axis=1)
combined['ineligible'] = combined['ineligible'].apply(lambda x: list(y for y in x))
combined['ineligible_count'] = combined['ineligible'].apply(lambda x: len(x))
just_committees = committee_data[['area', 'Committees']]
combined = combined.merge(just_committees, on='area', how='inner')
return combined
def get_committee_assignments(to_assign_areas, area_committees, committee_counts):
area_committees['is_last_year'] = area_committees['assignment_count'] == 0
area_committees.sort_values(by=['is_last_year', 'assignment_count'], ascending=[True, True], inplace=True)
filepath = 'area_committees.xlsx'
area_committees.to_excel(filepath, index=False)
queue = to_assign_areas
comm_copy = area_committees.copy()
successful = False
while queue:
# sort by fewest options
queue.sort(key=lambda a: comm_copy.loc[comm_copy['area']==a,'assignment_count'].iloc[0])
progress = False
for area in queue.copy():
successful, new_copy = assign(comm_copy, area, committee_counts)
if successful:
progress = True
comm_copy = new_copy
queue.remove(area)
if not progress:
return None
comm_copy.to_excel('comm_copy.xlsx', index=False)
print(comm_copy.head())
return comm_copy
def assign(comm_copy, area, committee_counts):
row = comm_copy[comm_copy['area'] == area]
if row['final_assignment'].iloc[0] is None:
comm_choices = row['assignment'].iloc[0] if isinstance(row['assignment'].iloc[0], list) else []
valid_committee = False
while not valid_committee:
if len(comm_choices) == 0:
return False, None
chosen_comm = random.choice(comm_choices)
count_row = committee_counts[committee_counts['Committee'] == chosen_comm]
comm_count = int(count_row['Assigned'].iloc[0]) + 1
print(comm_count)
if comm_count <= count_row['Max'].iloc[0]:
committee_counts.loc[committee_counts['Committee'] == chosen_comm, 'Assigned'] = comm_count
comm_copy.loc[comm_copy['area'] == area, 'final_assignment'] = chosen_comm
ineligible_arcs = comm_copy[comm_copy['area'] == area]['ineligible'].iloc[0]
for arc in ineligible_arcs:
if arc != 'nan':
arc_row = comm_copy[comm_copy['area'] == int(arc)]
choices = arc_row['assignment'].iloc[0]
if chosen_comm in choices:
choices.remove(chosen_comm)
valid_committee = True
else:
comm_choices.remove(chosen_comm)
print(comm_choices)
if len(comm_choices) == 0:
return False, None
return True, comm_copy
return True, comm_copy
def get_current_committees(year, committee_data):
current_comm = pd.DataFrame(columns=['Area', 'Committee'])
current_comm['Area'] = committee_data['Area'].astype(int)
current_comm['Committee'] = committee_data[str(year - 1951)]
current_comm.sort_values(by='Area', inplace=True)
return current_comm
def get_committee_counts_file(area_committees):
committee_counts = get_file('committee_counts.csv')
assigned_counts = area_committees['final_assignment'].value_counts().reset_index()
assigned_counts.columns = ['Committee', 'Assigned']
committee_counts = assigned_counts.merge(committee_counts, on='Committee', how='inner')
committee_counts['Assigned'] = committee_counts['Assigned'].fillna(0).astype(int)
return committee_counts
def is_solved(assignments, committee_counts):
if assignments is None or committee_counts is None:
return False
counts = assignments['final_assignment'].value_counts().reset_index()
counts = counts.rename(columns={'final_assignment': 'Committee'})
counts = counts.merge(committee_counts, on='Committee', how='inner')
counts['max_valid'] = counts['count'] <= counts['Max']
counts['min_valid'] = counts['count'] >= counts['Min']
counts['all_valid'] = counts['max_valid'] & counts['min_valid']
print(counts)
if not counts['all_valid'].all():
return False
return True
def get_committee_map(assigned_areas, current_committees):
committee_map = {}
for area in assigned_areas:
row = current_committees[current_committees['Area'] == area]
if not row.empty:
committee = row['Committee'].iloc[0]
committee_map[area] = committee
return committee_map
def get_area_committees(to_assign_areas, assigned_areas, committees, committee_map, combined_arcs):
combined_arcs['arc_comms'] = None
combined_arcs['assignment'] = None
combined_arcs['assignment_count'] = 0
combined_arcs['final_assignment'] = None
for area in to_assign_areas:
idx = combined_arcs.index[combined_arcs['area'] == area][0]
row = combined_arcs[combined_arcs['area'] == area]
arcs = row['ineligible'].iloc[0] if isinstance(row['ineligible'].iloc[0], list) else []
arc_comms = []
for x in arcs:
comm = committee_map.get(int(x)) if x != 'nan' else None
if comm:
arc_comms.append(comm)
recent_comms = row['Committees'].iloc[0].split(',') if isinstance(row['Committees'].iloc[0], str) else []
if len(recent_comms) > 0:
arc_comms.extend(x for x in recent_comms if x not in arc_comms)
if len(arc_comms) != 0:
combined_arcs.at[idx, 'arc_comms'] = arc_comms
assignment_options = [item for item in committees if item not in arc_comms]
combined_arcs.at[idx, 'assignment'] = assignment_options
combined_arcs.at[idx, 'assignment_count'] = len(assignment_options)
for area in assigned_areas:
comm = committee_map.get(area)
idx = combined_arcs.index[combined_arcs['area'] == area][0]
combined_arcs.at[idx, 'assignment'] = [comm]
combined_arcs.at[idx, 'final_assignment'] = comm
return combined_arcs
class DelegateAssign:
def __init__(self, year):
self.year = year
self.eo = 'even' if (year % 2) == 0 else 'odd'
self.all_areas = [x for x in range(1, 94)]
self.to_assign_areas = self.get_new_areas()[0]
self.assigned_areas = self.get_new_areas()[1]
self.committees = ['Agenda', 'Cooperation with the Professional Community', 'Corrections', 'Finance', 'Grapevine and La Viña', 'Literature', 'Policy and Admissions', 'Public Information', 'Report and Charter','Treatment and Accessibilities','Trustees']
def get_new_areas(self):
odds = [1, 4, 5, 6, 10, 11, 13, 14, 15, 17, 19, 21, 22, 24, 27, 30, 32, 33, 36, 38, 39, 40, 42, 44, 47, 49, 51, 52, 53, 54, 57, 59, 60, 65, 67, 69, 71, 72, 73, 75, 79, 82, 83, 85, 88, 89, 91, 93]
evens = [2, 3, 7, 8, 9, 12, 16, 18, 20, 23, 25, 26, 28, 29, 31, 34, 35, 37, 41, 43, 45, 46, 48, 50, 55, 56, 58, 61, 62, 63, 64, 66, 68, 70, 74, 76, 77, 78, 80, 81, 84, 86, 87, 90, 92]
return (evens, odds) if self.eo == 'even' else (odds, evens)
def assign_delegates(self):
attempt = 0
max_attempts = 50
was_successful = False
while not was_successful and attempt < max_attempts:
attempt += 1
print(f"Attempt {attempt}")
# Reload fresh data each attempt
committee_data = get_file('committee_data.csv')
committee_data['area'] = committee_data['Area']
(to_assign_areas, assigned_areas) = self.get_new_areas()
combined_arcs = get_arcs(committee_data)
current_comm = get_current_committees(self.year, committee_data)
committee_map = get_committee_map(assigned_areas, current_comm)
area_committees = get_area_committees(to_assign_areas, assigned_areas, self.committees, committee_map, combined_arcs)
committee_counts = get_committee_counts_file(area_committees)
new_committees = get_committee_assignments(to_assign_areas, area_committees, committee_counts)
was_successful = is_solved(new_committees, committee_counts.copy())
if was_successful:
print("✅ Successful assignment on attempt", attempt)
return new_committees
print("❌ Failed after", attempt, "attempts")
return None
assignments = DelegateAssign(2026).assign_delegates()
assignments = assignments[['area', 'final_assignment']]
filepath = 'assignments.xlsx'
if assignments is not None:
assignments.to_excel(filepath, index=False)