-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortingAlgo.py
393 lines (309 loc) · 9.43 KB
/
sortingAlgo.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
import random, copy, string, sys
from multiprocessing import Pool
"""
top three methods are helpers to generate data before I had any good info
"""
# Generate a fake netid
def makeNetid():
netidString = ''.join((random.choice(string.ascii_lowercase) for x in range(5)))
netidString += ''.join((random.choice(string.digits) for x in range(2)))
return netidString
# Generate a list of discussions
def makeChoiceBucket():
days = ['TH', 'FR']
times = [x for x in range(8, 22, 2)]
timesodd = [x for x in range(9, 23, 2)]
bestTimes = [13, 14, 15, 16]
#sections = ['S1','S2']
bucket = []
for x in days:
for y in times:
if y in bestTimes:
bucket.append(x + ' ' + str(y))
bucket.append(x + ' ' + str(y))
for y in timesodd:
if y in bestTimes:
bucket.append('TH' + ' ' + str(y))
bucket.append('TH' + ' ' + str(y))
return bucket
# Generating arbitrary choices for fake students
def generateDataset(choices):
f = open('sampleDataset', 'w')
bucket = makeChoiceBucket()
for x in range(205):
netid = makeNetid()
sections = []
while len(sections) < choices:
sec = random.choice(bucket)
if sec not in sections:
sections.append(sec)
f.write(netid + ',' +' ' + ', '.join(sections) + '\n')
# Calculating the score for this discussion section assignment
def prefsScore(disc):
prefs = [0 for x in range(20)]
highestChoice = 0
for key, dis in disc.items():
for i, disSec in enumerate(dis):
for stu in disSec.students:
prefs[stu.discussion] += 1
if stu.discussion > highestChoice:
highestChoice = stu.discussion
score = 0
prefs = prefs[:highestChoice+1]
for i, pref in enumerate(prefs):
score += pref * 2**(i*2)
return prefs, score
# Student class
class student:
def __init__(self, line):
self.choices = []
self.cannot = []
# If they didn't follow the rules, I flag them
self.redFlag = False
data = line.split('"')
nopes = []
if len(data) > 1:
nopes = data[-2].split(', ')
data = data[0].split(',')
self.netid = data[1].split('@')[0]
yeps = data[2:]
# Yeps are sections they want to do, nopes are the ones they cant
for yep in yeps:
if len(yep) > 1:
yepLabels = yep.split(' ')
day = 'TH' if yepLabels[0] == 'Thursday' else 'FR'
timeString = yepLabels[2]
time = int(timeString.split(':')[0])
if time != 12 and 'pm' in timeString:
time += 12
self.choices.append(day + ' ' + str(time))
for nope in nopes:
if len(nope) > 1:
nopeLabels = nope.split(' ')
day = 'TH' if nopeLabels[0] == 'Thursday' else 'FR'
timeString = nopeLabels[2]
time = int(timeString.split(':')[0])
if time != 12 and 'pm' in timeString:
time += 12
self.cannot.append(day + ' ' + str(time))
if len(self.choices)!=len(set(self.choices)):
self.redFlag = True
self.ranking = 0
self.discussion = 0
def assignDiscussion(self, disc):
self.discussion = self.choices.index(disc.time)
def addRestOfChoices(self, discussions):
# take list of discussions - choices - nope, scramble add to choices
leftOver = list(set(discussions) - set(self.choices) - set(self.cannot))
if len(leftOver) == 0:
self.redFlag = True
# print self.netid
for dis in scrambled(leftOver):
self.choices.append(dis)
def __repr__(self):
return self.netid
# discussion class
class discussion:
def __init__(self, line):
self.name = line
self.time = ' '.join(line.split(' ')[:2])
self.students = []
self.potentialStudents = []
def isFull(self):
return True if len(self.students) == 6 else False
def addStudent(self, student):
self.students.append(student)
student.assignDiscussion(self)
# crux of the marriage algorithm
def askToGetIn(self, stu):
maxStu = self.students[0]
for disStu in self.students:
if disStu.ranking > maxStu.ranking:
maxStu = disStu
if stu.ranking < maxStu.ranking:
self.students.remove(maxStu)
self.students.append(stu)
stu.assignDiscussion(self)
return (True, maxStu)
else:
return (False, None)
def __repr__(self):
return str(self.students)
# get a random arrangement of the array
def scrambled(orig):
dest = orig[:]
random.shuffle(dest)
return dest
# randomize algorithm to see if it would behave better
def randomizedAlgo(students, discussions):
studentsAssigned = []
studentsNotAssigned = []
while len(students) > 0:
stu = random.choice(students)
assigned = False
for dis in stu.choices:
for disSec in discussions[dis]:
if not disSec.isFull():
disSec.addStudent(stu)
assigned = True
break;
if assigned:
studentsAssigned.append(stu)
break;
if not assigned:
studentsNotAssigned.append(stu)
students.remove(stu)
return studentsAssigned, studentsNotAssigned
def marriage(students, discussions):
# each discussion needs a "priority" list for the students it wants in its section. For the sake of consistency, every discussion has the same student ranking
randoRanking = scrambled(students)
for i, stu in enumerate(students):
stu.ranking = randoRanking.index(stu)
married = []
notMarried = students
unwantedStudents = []
# whilst there are students to be married, try to add it into a discussion
while len(notMarried) > 0:
stu = random.choice(notMarried)
unwanted = True
for dis in stu.choices:
noFreeSpots = True
# add to first discussion based on student's preferences
for disSec in discussions[dis]:
if not disSec.isFull():
disSec.addStudent(stu)
married.append(stu)
notMarried.remove(stu)
noFreeSpots = False
unwanted = False
break;
# we can ask to get into a discussion, if discussion has someone that's ranked lower, it will kick them out in favor of this student with a higher rank
if noFreeSpots:
for disSec in discussions[dis]:
askResult = disSec.askToGetIn(stu)
# result is (bool, student kicked out)
if askResult[0]:
married.append(stu)
notMarried.remove(stu)
notMarried.append(askResult[1])
married.remove(askResult[1])
unwanted = False
break;
if not unwanted:
break;
if unwanted:
unwantedStudents.append(stu)
notMarried.remove(stu)
return married, unwantedStudents
# randomized iteration, if all students are put into sections, we break and return, otherwise, try again
def iteration((students, discussions)):
for stu in students:
stu.addRestOfChoices(discussions.keys())
count = 0
while True:
count += 1
stuInst = copy.deepcopy(students)
discInst = copy.deepcopy(discussions)
marResult = marriage(stuInst, discInst)
if len(marResult[1]) == 0:
break;
#print count,
return discInst
# gets all students with redflags
def getRedFlags(fileName):
exceptions = []
f = open(fileName, 'r')
data = f.read().split('\n')[1:]
f.close()
students = []
for dat in data:
students.append(student(dat))
checkWhoRegistered(students)
f = open('discussions', 'r')
data = f.read().split('\n')
f.close()
w = open('redFlags', 'w')
redFlagCount = 0
discussions = {}
for dat in data:
time = dat.split(' ')
if ' '.join(time[:-1]) not in discussions.keys():
discussions[' '.join(time[:-1])] = []
discussions[' '.join(time[:-1])].append(discussion(dat))
for stu in students:
stu.addRestOfChoices(discussions.keys())
if stu.redFlag and stu.netid not in exceptions:
redFlagCount += 1
w.write(stu.netid + ' ' + str(stu.choices) + '\n')
w.close()
print 'Red flags:', redFlagCount
# cross referencing who has registered and who has not
def checkWhoRegistered(registered):
f = open('students', 'r')
roster = f.read().split('\n')
f.close()
notInOfficialRoster = []
notRegistered = []
for stu in registered:
if stu.netid in roster:
roster.remove(stu.netid)
else:
notInOfficialRoster.append(stu.netid)
for stu in roster:
notRegistered.append(stu)
print 'Not registered:', len(notRegistered)
w = open('notRegistered', 'w')
w.write('Not Registered' + '\n')
w.write(str(notRegistered) + '\n')
w.write("Not in Official Roster" + '\n')
w.write(str(notInOfficialRoster))
w.close();
# write a file with the sorting score
def writeToFile(discInst, score):
f = open('assignments/sectionAssignments' + str(score), 'w')
sortedKeys = sorted(discInst.keys())
for key in sortedKeys:
dis = discInst[key]
for i, disSec in enumerate(dis):
f.write(key + ' S' + str(i) + ', ' + ', '.join(str(x) for x in disSec.students) + '\n')
f.close()
minScore = 10000000
iterations = int(sys.argv[1])
fileName = sys.argv[2]
getRedFlags(fileName)
jobs = []
f = open(fileName, 'r')
data = f.read().split('\n')[1:]
f.close()
students = []
for dat in data:
students.append(student(dat))
f = open('discussions', 'r')
data = f.read().split('\n')
f.close()
discussions = {}
for dat in data:
time = dat.split(' ')
if ' '.join(time[:-1]) not in discussions.keys():
discussions[' '.join(time[:-1])] = []
discussions[' '.join(time[:-1])].append(discussion(dat))
pool = Pool(processes=8)
# mutlithreading for the win
poolParams = []
for x in range(8):
poolParams.append((copy.deepcopy(students), copy.deepcopy(discussions)))
for i in range(iterations):
if i % 100 == 0:
print '---',i,'---'
for x in range(8):
poolParams[x] = (copy.deepcopy(students), copy.deepcopy(discussions))
for resultDisc in pool.map(iteration, poolParams):
prefScore = prefsScore(resultDisc)
#print prefScore[1],
if prefScore[1] < minScore:
writeToFile(resultDisc, prefScore[1])
minScore = prefScore[1]
print 'written', prefScore[1], prefScore[0]
#resultDisc = iteration(fileName)
#print prefsScore(resultDisc, 10)
#writeToFile(resultDisc)