-
Notifications
You must be signed in to change notification settings - Fork 0
/
ELM_Team_Formation_Code.py
1142 lines (733 loc) · 39.1 KB
/
ELM_Team_Formation_Code.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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
from itertools import combinations as comb
import time
import random
import tkinter as tk
#get_ipython().run_line_magic('gui', 'tk')
# # Common Functions for All
# In[2]:
def write_csv(names,groups,group_constraints,input_file, output_file):
import csv
import datetime
def calculate_group_happiness(g,gc):
s=0 # Variable to store the "satisfaction"
nums = np.arange(0,len(g),1) # Indices for each person in the group
all_pairs = list(comb(nums,2)) # All pairs of individuals
for pair in all_pairs:
pair_score = score(gc[pair[0]],gc[pair[1]])
s = s + pair_score
return s
print_satisfaction = 0 # Should we print the satisfaction?
max_poss_happiness = 1
if(len(group_constraints)!=0):
print_satisfaction=1 # Don't print in case of indeterminate groups
dummy_group = []
dummy_group_constraints = []
for i in range(0,len(group_constraints[0])):
dummy_prefs = []
dummy_group.append("person"+str(i+1))
for j in range(0,len(group_constraints[0][0])):
dummy_prefs.append("dummy"+str(j+1))
dummy_group_constraints.append(dummy_prefs)
dummy_group_constraints=np.array(dummy_group_constraints)
max_poss_happiness=calculate_group_happiness(dummy_group,dummy_group_constraints)
print()
print("Maximum possible happiness is: "+str(max_poss_happiness))
print("Creating output CSV.")
print("Groups written to file: ",end=" ")
data = pd.read_csv(input_file)
date = datetime.datetime.now()
dateString = date.strftime("-%Y-%b-%d_%H-%M-%S")
fileName = output_file+dateString+".csv"
counter = 0
personCounter = 0
with open(fileName, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(np.append(["Group Number","Satisfaction"],data.columns.values)) # Write the first line with column headers
for i in range(0,len(groups)):
group = groups[i]
if(print_satisfaction>0):
group_happiness = calculate_group_happiness(groups[i],group_constraints[i])
satisfaction = str(np.round(100.0*(group_happiness/max_poss_happiness),2))+"%" # This the "percentage" of happiness
else:
satisfaction = "Not defined"
#writer.writerow(["Group "+str(counter+1),"","Satisfaction: "+satisfaction])
for person in group:
if(person[0:8]!="!phantom"): # Don't print phantoms
personCounter = personCounter + 1
index = np.where(names==person)[0][0]
line = data.iloc[[index]].fillna('').values[0]
writer.writerow(np.append([str(counter+1),satisfaction],line))
writer.writerow([])
counter = counter + 1
print(counter,end=" ")
print()
print("Done creating CSV.")
print()
print("Total students processed: "+str(personCounter))
def score(list1,list2): # accept 2 lists to compare
num = 0 # to store rating of lists
t = len(list1) # total number of preferences
for i in range(0,len(list1)):
for j in range(0,len(list2)):
if(list1[i]==list2[j]): # If any element of list1 is present in list2
num = num + ((t-i)*(t-j))**2 # (in any order) increment num
for i in range(0,len(list1)): # if order is the same, add extra
if(list1[i]==list2[i]): # points. If 1st pref same, add 12
num = num + int((24/(i+1))**2) # for 2nd, add 6, and 3rd 4
return num
def happiness(group,names,pair_rating): # group is a "group" [name1, name2]
# Remarkably, this also works when "group" is a pair of two groups!
# Which is why it is *also* used in the group_pairs function!
nums = []
names = np.array(names)
for i in range(0,len(group)):
nums.append(np.where(names==group[i])[0][0])
pairs_in_group = list(comb(nums,2))
happiness = 0
for pair in pairs_in_group:
happiness = happiness + pair_rating[pair[0]][pair[1]]
return(happiness)
# # Code to create Quartets
# In[3]:
def pair_groupmates(names,preferred_groupmate,constraints):
print("Begin pairing preferred teammates.")
# Assumptions in this function:
# 1) All members are paired with one and only one other member
# 2) Pairs are unique (A-->C => C-->A)
# 3) All pair members have exactly the same preferences (constraints)
### TEST ARRAYS FOR DEBUGGING #################################
#
# names = np.array(["A","B","C","D","E","F"])
# preferred_groupmate = np.array(["", "E", "D","C" ,"B",""])
# d1 = [1,2,3,3,2,0]
# d2 = [6,7,8,8,7,10]
# d3 = [11,12,13,13,12,20]
# constraints = np.array([d1,d2,d3])
# print(constraints)
###############################################################
groups = []
group_constraints = []
new_names=[]
new_constraints = []
i=0
while(i<len(names)):
if(preferred_groupmate[i]==''):
new_names.append(names[i])
new_constraints.append(constraints[:,i].tolist())
i=i+1
continue
pair = [names[i],preferred_groupmate[i]]
groups.append(pair)
index = np.where(preferred_groupmate == names[i])
if(len(index[0])>1):
print("ERROR! " + names[i] + " has been chosen twice!")
break
elif(len(index[0])==1):
temp = index[0][0]
group_constraints.append([constraints[:,i].tolist(),constraints[:,temp].tolist()])
names = np.delete(names,temp)
preferred_groupmate = np.delete(preferred_groupmate,temp)
constraints = np.delete(constraints,temp,axis=1)
i = i+1
# The new_constraints here is a little odd, while in this function we use constraints[:,index] to
# get a person's preferences, if you wanted to do the same thing with new_constraints, you need to use
# new_constraints[index,:]. I'd try to fix it, but it doesn't really matter and I can't be too bothered.
print("Done pairing preferred teammates.")
return new_names, new_constraints, groups, group_constraints
# In[4]:
def pair_remaining(names,constraints,groups,group_constraints):
print("Begin pairing remaining students.")
print("Students remaining:",end=" ")
names = np.array(names)
constraints = np.array(constraints) # Check final comment in pair_groupmates regarding how this is indexed.
while(len(names)>0):
N = len(names)
pair_rating = np.zeros((N,N),int)
## Create pair_ratings based on the provided names array
for i in range(0,N):
for j in range(i+1,N):
s = score(constraints[i,:],constraints[j,:])
pair_rating[i,j]=s
pair_rating[j,i]=s
## Finding the best match among all pairs of students provided by the names array
all_pairs = list(comb(names,2)) # List of all pairs of students
happiness_array = [] # Array to store the happiness of each pair
# Find happiness for every pair
for i in range(0, len(all_pairs)):
happiness_array.append(happiness(all_pairs[i],names,pair_rating))
happiness_array=np.array(happiness_array) # Convert it to a numpy array
max_val = max(happiness_array) # Find maximum value of the happiness array.
pair_nums = np.where(happiness_array==max_val)[0] # Find pairs that have this max_val. Returns an array
# since there may be more than one result. The array
# contains integers that represent the position of the pair
# in the happiness_array / all_pairs lists.
#### COULD BE BETTER -- Right now choosing randomly
# Since there could be many pairs that have the same "largest" value of happiness, and since
# the same student(s) may be present in multiple pairs, we have a slight problem. To circumvent this, I
# have decided to choose a pair at random. However, I continue to use pair_nums as if it were an array of pairs
# so that if I want to improve on this later, I don't need to change the code.
# Ideally, I'd like to remove all cases where the same person exists in more than one pair (by, say, choosing
# one of *those* pairs randomly), and then pair up all the rest. But frankly, now that I think about it, I
# don't think it'd really be very different from what I'm doing now.
pair_nums = [random.choice(pair_nums)]
for pair in pair_nums:
people = all_pairs[pair]
sample = [people[0],people[1]] # Group with names instead of numbers
sample_constraints = []
for person in sample:
index = np.where(names==person)[0][0]
sample_constraints.append(constraints[index,:])
names = np.delete(names,index)
constraints = np.delete(constraints, index, axis = 0)
groups.append(sample)
group_constraints.append(sample_constraints)
print(len(names),end=" ")
print()
print("Done pairing remaining students.")
return groups, group_constraints
# In[5]:
def groups_pairs(groups,group_constraints):
print("Begin creating quartets.")
print("Pairs remaining:",end=" ")
groups, group_constraints = np.array(groups), np.array(group_constraints)
# The idea here is to group the pairs by similar interests. We will again need to make a "pair_ratings"
# type table, and pick out the pairs that have a maximum value. This function should thus follow very
# closely the logic of the function pair_remaining.
final_quartets = [] # Array to store results of final quartets.
final_quartet_constraints = [] # Array to store constraints of final quartets
while(len(groups)>0):
N = len(groups)
quartet_rating = np.zeros((N,N),int) # We now have groups of 4, so it's a quartet rating
## Create quartet_ratings based on the provided groups array
for i in range(0,N):
for j in range(i+1,N):
# The two groups to compare are now groups[i] and groups[j], each with their own 'interests'
# group_constraints[i,:], group_constraints[j,:].
# To calculate the score of the potential team formed by [A, B] and [C, D], I calculate the
# score(A,C) + score(B,D) + score(A,D) + score(B,C). I *do not* add to it the score of (A,B) and
# (C,D), to avoid groups having a very strong compatibility mucking it up for everyone else.
# Below is a simple piece of code you can uncomment to see how the score is calculated
# print("Groups formed by", groups[i], " and ", groups[j])
# print(groups[i][0], " ", groups[j][0])
# print(group_constraints[i,:][0],"\n",group_constraints[j,:][0])
# print(groups[i][1], " ", groups[j][1])
# print(group_constraints[i,:][1],"\n",group_constraints[j,:][1])
# print(groups[i][0], " ", groups[j][1])
# print(group_constraints[i,:][0],"\n",group_constraints[j,:][1])
# print(groups[i][1], " ", groups[j][0])
# print(group_constraints[i,:][1],"\n",group_constraints[j,:][0])
# s below uses the algorithm mentioned above s(AC) + s(BD) + s(AD) + s(BC)
s = score(group_constraints[i,:][0],group_constraints[j,:][0]) + score(group_constraints[i,:][1],group_constraints[j,:][1]) + score(group_constraints[i,:][1],group_constraints[j,:][0]) + score(group_constraints[i,:][0],group_constraints[j,:][1])
quartet_rating[i,j]=s
quartet_rating[j,i]=s
## Finding the best match among all pairs of pairs provided by the groups array
all_quartets = list(comb(groups.tolist(),2)) # List of all pairs of pairs of students
happiness_array = [] # Array to store the happiness of each quartet
# Find happiness for every quartet
for i in range(0, len(all_quartets)):
happiness_array.append(happiness(all_quartets[i],groups,quartet_rating))
happiness_array=np.array(happiness_array) # Convert it to a numpy array
max_val = max(happiness_array) # Find maximum value of the happiness array.
quartet_nums = np.where(happiness_array==max_val)[0] # Find quartets that have this max_val. Returns an array
# since there may be more than one result. The array
# contains integers that represent the position of the
# quartet in the happiness_array / all_quartets lists.
#### COULD BE BETTER -- Right now choosing randomly
# Since there could be many quartets that have the same "largest" value of happiness, and since
# the same pair(s) may be present in multiple quartets, we have a slight problem. To circumvent this, I
# have decided to choose a quartet at random. However, I continue to use quartet_nums as if it were an array of pairs
# so that if I want to improve on this later, I don't need to change the code.
# Ideally, I'd like to remove all cases where the same pair exists in more than one quartet (by, say, choosing
# one of *those* quartets randomly), and then pair up all the rest. But frankly, now that I think about it, I
# don't think it'd really be very different from what I'm doing now.
quartet_nums = [random.choice(quartet_nums)]
for quartet in quartet_nums:
pairs = all_quartets[quartet]
sample = pairs[0].copy() # Make a copy of the first pair
for person in pairs[1]:
sample.append(person) # Append to this copy all people in second pair.
# The variable sample now has a full quartet
sample_constraints = [] # Array to store constraints of quartet
for pair in pairs:
index = np.where(groups==pair)[0][0]
for constraint in group_constraints[index,:]:
sample_constraints.append(constraint.tolist())
groups = np.delete(groups,index,axis=0) # Axis is important! Pay attention.
group_constraints = np.delete(group_constraints, index, axis = 0)
final_quartets.append(sample)
final_quartet_constraints.append(sample_constraints)
print(len(groups),end=" ")
print()
print("Done creating quartets.")
return final_quartets, final_quartet_constraints
# # Code to create Groups of Indeterminate Sizes
# In[6]:
def create_indeterminate_groups(new_names, new_d1, new_d2, new_d3, new_d4, new_d5):
N = len(new_names)
pref = np.zeros((N,N),int)
for i in range(0,N):
for j in range(i+1,N):
s = score([new_d1[i],new_d2[i],new_d3[i],new_d4[i],new_d5[i]],[new_d1[j],new_d2[j],new_d3[j],new_d4[j],new_d5[j]])
pref[i,j]=s
pref[j,i]=s
class_pairs = list(comb(new_names,2))
happiness_array = []
for i in range(0, len(class_pairs)):
happiness_array.append(happiness(class_pairs[i],new_names,pref))
happiness_array=np.array(happiness_array)
max_val = max(happiness_array)
pair_nums = np.where(happiness_array==max_val)[0]
#### COULD BE BETTER -- Right now choosing randomly
pair_nums = [random.choice(pair_nums)]
for pair in pair_nums:
people = class_pairs[pair]
sample = np.array([people[0],people[1]])
pref1 = []
pref2 = []
pref3 = []
pref4 = []
pref5 = []
for person in sample:
index = np.where(new_names==person)[0][0]
pref1.append(new_d1[index])
pref2.append(new_d2[index])
pref3.append(new_d3[index])
pref4.append(new_d4[index])
pref5.append(new_d5[index])
new_names = np.delete(new_names,index)
new_d1 = np.delete(new_d1,index)
new_d2 = np.delete(new_d2,index)
new_d3 = np.delete(new_d3,index)
new_d4 = np.delete(new_d5,index)
new_d5 = np.delete(new_d5,index)
new_names = np.append(new_names,str(sample[0])+"-"+str(sample[1]))
##### COULD BE BETTER -- Currently random choice
##### is made between 1st,2nd,3rd preferences respectively
new_d1 = np.append(new_d1,random.choice(pref1))
new_d2 = np.append(new_d2,random.choice(pref2))
new_d3 = np.append(new_d3,random.choice(pref3))
new_d4 = np.append(new_d4,random.choice(pref4))
new_d5 = np.append(new_d5,random.choice(pref5))
print(len(new_names),end=" ")
return new_names,new_d1,new_d2,new_d3,new_d4,new_d5,max_val
# # Code for Groups of Four (BETA)
# In[7]:
def beta_all_possible_quartets(names,constraints):
# names = np.append(names,["G","H","I","J"])
# constraints = np.append(constraints,[[1,2,3]],axis=0)
# constraints = np.append(constraints,[[1,2,3]],axis=0)
# constraints = np.append(constraints,[[1,2,3]],axis=0)
# constraints = np.append(constraints,[[1,2,3]],axis=0)
groups = []
constraints = np.array(constraints)
print("Groups of 4+ created ",end=" ")
while(len(names)>0):
N = len(names)
print("N"+str(N),end=" ")
quartet_rating = np.zeros((N,N),int)
## Create pair_ratings based on the provided names array
for i in range(0,N):
for j in range(i+1,N):
s = score(constraints[i],constraints[j])
quartet_rating[i,j]=s
quartet_rating[j,i]=s
all_quartets = list(comb(names,4))
happiness_array = []
for i in range(0, len(all_quartets)):
happiness_array.append(happiness(all_quartets[i],names,quartet_rating))
happiness_array=np.array(happiness_array) # Convert it to a numpy array
max_val = max(happiness_array) # Find maximum value of the happiness array.
quartet_nums = np.where(happiness_array==max_val)[0] # Find quartets that have this max_val. Returns an array
# since there may be more than one result. The array
# contains integers that represent the position of the pair
# in the happiness_array / all_quartet lists.
#### COULD BE BETTER -- Right now choosing randomly
# Since there could be many quartets that have the same "largest" value of happiness, and since
# the same pair(s) may be present in multiple quartets, we have a slight problem. To circumvent this, I
# have decided to choose a quartet at random. However, I continue to use quartet_nums as if it were an array of pairs
# so that if I want to improve on this later, I don't need to change the code.
# Ideally, I'd like to remove all cases where the same pair exists in more than one quartet (by, say, choosing
# one of *those* quartets randomly), and then pair up all the rest. But frankly, now that I think about it, I
# don't think it'd really be very different from what I'm doing now.
quartet_nums = [random.choice(quartet_nums)]
for quartet_num in quartet_nums: # Get a group of four
quartet = all_quartets[quartet_num] # Get the list of students in quartet
for person in quartet:
index = np.where(names==person)[0][0]
names = np.delete(names,index)
constraints = np.delete(constraints,index,axis=0)
groups.append(list(quartet))
print(len(groups),end=" ")
print()
print("Done creating quartets.")
group_constraints = np.array([])
return groups,group_constraints
# # Functions called directly by GUI
# In[8]:
def run_groups_of_four(names,preferred_groupmate,constraints,input_filename, output_filename):
print("******** CREATING GROUPS OF FOUR ********")
print()
# Make groups out of the team member preferences
new_names, new_constraints, groups, group_constraints = pair_groupmates(names,preferred_groupmate,constraints)
# Assign the remaining students to groups based on constraints (project preferences etc.)
groups, group_constraints = pair_remaining(new_names,new_constraints,groups,group_constraints)
# Make groups of 4 out of the pairs
quartets, quartet_constraints = groups_pairs(groups,group_constraints)
# Write resulting groups to a .csv file
write_csv(names, quartets, quartet_constraints, input_filename, output_filename)
def run_groups_of_two(names,preferred_groupmate,constraints,input_filename,output_filename):
print("******** CREATING GROUPS OF TWO ********")
print()
# Make groups out of the team member preferences
new_names, new_constraints, groups, group_constraints = pair_groupmates(names,preferred_groupmate,constraints)
# Assign the remaining students to groups based on constraints (project preferences etc.)
groups, group_constraints = pair_remaining(new_names,new_constraints,groups,group_constraints)
# Write resulting groups to a .csv file
write_csv(names, groups, group_constraints, input_filename, output_filename)
def run_indeterminate_groups(names,preferred_groupmate,constraints,max_groups,input_filename,output_filename):
print("******** CREATING GROUPS OF INDETERMINATE SIZES ********")
print()
## This part of the code assumes both preferred teammates have same preferences.
# Make groups out of the team member preferences
new_names, new_constraints, paired_teammates, paired_constraints = pair_groupmates(names,preferred_groupmate,constraints)
print(len(new_names),end=" ")
for i in range(0,len(paired_teammates)):
group = paired_teammates[i]
if(len(group)>2):
print("ERROR! More than two preferred teammates paired together. Output unreliable.")
temp = group[0]+"-"+group[1]
new_names.append(temp)
new_constraints.append(paired_constraints[i][0]) # Assuming both teammates have same preferences, so
# only appending the preferences of the first
new_names = np.array(new_names)
new_constraints = np.array(new_constraints)
new_d1 = new_constraints[:,0].copy()
new_d2 = new_constraints[:,1].copy()
new_d3 = new_constraints[:,2].copy()
new_d4 = new_constraints[:,3].copy()
new_d5 = new_constraints[:,4].copy()
print("Starting pairing.")
print("Groups remaining: ",end=" ")
while(len(new_names)>max_groups):
new_names, new_d1, new_d2, new_d3, new_d4, new_d5, val = create_indeterminate_groups(new_names,new_d1,new_d2,new_d3,new_d4,new_d5)
print(len(new_names),end=" ")
print("Done pairing.")
groups = []
for group in new_names:
members = group.split("-")
groups.append(members)
group_constraints = np.array([]) # As of right now, we can't measure a score for indeterminate groups.
write_csv(names,groups,group_constraints,input_filename,output_filename)
def run_beta_groups_of_four(names,preferred_groupmate,constraints,input_filename,output_filename):
print("******** CREATING GROUPS OF FOUR (BETA) ********")
print()
names_copy = names.copy()
# Make groups out of the team member preferences
new_names, new_constraints, groups, group_constraints = pair_groupmates(names,preferred_groupmate,constraints)
## Add paired teammates as new individuals ##
temp_name_array = []
for group in groups:
temp_name = ""
for person in group:
temp_name = temp_name + person + "-"
temp_name=temp_name[:-1]
temp_name_array.append(temp_name)
new_names = np.append(new_names,temp_name_array)
#print(new_constraints)
print(len(new_names))
## Add paired constraints to the list
for group_constraint in group_constraints:
new_constraints.append(group_constraint[0])
#### DELETE THIS SECTION ONCE IT'S IMPROVED ####
phantomNo = 1
if(len(new_names)%4==3):
new_names,preferred_groupmate,new_constraints,phantomNo = add_one_phantom(new_names,preferred_groupmate,new_constraints,phantomNo)
if(len(new_names)%4==2):
new_names,preferred_groupmate,temp_constraints,phantomNo = add_one_phantom(new_names,preferred_groupmate,new_constraints,phantomNo)
new_names,preferred_groupmate,temp_constraints,phantomNo = add_one_phantom(new_names,preferred_groupmate,new_constraints,phantomNo)
new_constraints = np.append(new_constraints,[[0,0,0,0,0]],axis=0)
new_constraints = np.append(new_constraints,[[0,0,0,0,0]],axis=0)
#print(new_constraints)
if(len(new_names)%4==1):
new_names,preferred_groupmate,new_constraints,phantomNo = add_one_phantom(new_names,preferred_groupmate,new_constraints,phantomNo)
new_names,preferred_groupmate,new_constraints,phantomNo = add_one_phantom(new_names,preferred_groupmate,new_constraints,phantomNo)
new_names,preferred_groupmate,new_constraints,phantomNo = add_one_phantom(new_names,preferred_groupmate,new_constraints,phantomNo)
print("New length of thing "+str(len(new_names)))
print("New length of const "+str(len(new_constraints)))
################################################
# Calculate quartets
quartets, quartet_constraints = beta_all_possible_quartets(new_names,new_constraints)
new_groups=[]
for quartet in quartets:
sample_group = []
for person in quartet:
members = person.split("-")
for member in members:
sample_group.append(member)
new_groups.append(sample_group)
print("Length of new groups "+str(len(new_groups)))
# Write resulting groups to a .csv file
write_csv(names_copy, new_groups, quartet_constraints, input_filename, output_filename)
# # Adding Phantom Students
# In[9]:
## Adding Phantom Students to make the numbers divisible by 4
def add_one_phantom(names,preferred_groupmate,constraints,phantomNo):
names = np.append(names,"!phantom"+str(phantomNo))
preferred_groupmate = np.append(preferred_groupmate,"")
dummy_constraint = []
for i in range(0,len(constraints)):
dummy_constraint.append("!pcriterion"+str(i+1))
constraints = np.c_[constraints,dummy_constraint]
phantomNo = phantomNo + 1
return names,preferred_groupmate,constraints,phantomNo
def add_two_phantom(names,preferred_groupmate,constraints,phantomNo):
# Add First Person
names = np.append(names,"!phantom"+str(phantomNo))
preferred_groupmate = np.append(preferred_groupmate,"!phantom"+str(phantomNo+1))
# Add Second Person
names = np.append(names,"!phantom"+str(phantomNo+1))
preferred_groupmate = np.append(preferred_groupmate,"!phantom"+str(phantomNo))
# Dummy constraints for both (they have the same), so appended twice
dummy_constraint = []
for i in range(0,len(constraints)):
dummy_constraint.append("!pcriterion"+str(i+1))
constraints = np.c_[constraints,dummy_constraint]
constraints = np.c_[constraints,dummy_constraint]
phantomNo = phantomNo + 2
return names,preferred_groupmate,constraints,phantomNo
# # The GUI (Main)
# In[10]:
from tkinter import *
import tkinter.messagebox as messagebox
import traceback
from tkinter import ttk
from tkinter import filedialog
from dadjokes import Dadjoke
import time
versionNumber = "1.1"
def browseFiles():
filename = filedialog.askopenfilename(initialdir = "./",
title = "Select a File",
filetypes = (("Text files",
"*.csv"),
("all files",
"*.*")))
# Change label contents
entryText.set(filename)
updateLists(filename)
def get_input():
try:
processingWindow = Toplevel()
processingWindow.title("Don't rush me!")
Label(processingWindow,
text="While I'm working, here's something you might appreciate:", width = 50,
justify = CENTER,
padx = 20).pack(pady=10)
try:
joke = Dadjoke().joke
except:
joke = "Why do birds fly south in winter?\n\n Because it's too far to walk."
Label(processingWindow,
text=joke, width = 50,
justify = CENTER, wraplength=300, fg='saddle brown',
padx = 20).pack(pady=10)
# progress=ttk.Progressbar(processingWindow,orient=HORIZONTAL,length=50,mode='indeterminate')
# progress.pack()
# progress.start()
processingWindow.update()
input_filename = fileName.get() # Get the name of the input file
data = pd.read_csv(input_filename)
names = data[uid_field.get()].values
preferred_groupmate = data[ptm_field.get()].fillna('').values
d_array = [c1.get(),c2.get(),c3.get(),c4.get(),c5.get()]
constraints = []
for element in d_array:
if(len(element)!=0):
constraints.append(data[element].values)
constraints = np.array(constraints)
#####################################################
## #####
## Dealing with odd numbers of people or groups #####
## As of now the code creates either groups of #####
## two or four, and so we need to make sure the #####
## arrays above are multiples of 4. This is not #####
## essential for the indeterminate sized groups.#####
## We add enough"phantom" students to do this. #####
## #####
#####################################################
print()
print("###### STARTING GROUP CREATION #####")
print("Total number of students: "+str(len(names)))
phantomNo = 1 # A counter for the number of phantom students added.
if(len(names)%4==3):
names,preferred_groupmate,constraints,phantomNo = add_one_phantom(names,preferred_groupmate,constraints,phantomNo)
elif(len(names)%4==2):
names,preferred_groupmate,constraints,phantomNo = add_two_phantom(names,preferred_groupmate,constraints,phantomNo)
elif(len(names)%4==1):
names,preferred_groupmate,constraints,phantomNo = add_one_phantom(names,preferred_groupmate,constraints,phantomNo)
names,preferred_groupmate,constraints,phantomNo = add_two_phantom(names,preferred_groupmate,constraints,phantomNo)
print("Number of phantoms added: "+ str(phantomNo-1) + " (Yay!)")
print()
button = v.get()
max_groups = int(max_groups_entry.get())
output_filename = output_file.get()
if button == 1:
if(len(names)%4!=0):
messagebox.showerror("What on Earth!","It seems that the number of students isn't a multiple of four.",detail="This error certainly shoudn't occur. Call Philip up and complain at once!")
else:
run_groups_of_four(names,preferred_groupmate,constraints,input_filename,output_filename)
elif button == 2:
if(len(names)%2!=0):
messagebox.showerror("What on Earth!","It seems that the number of students isn't a multiple of two.",detail="This error certainly shoudn't occur. Call Philip up and complain at once!")
else:
run_groups_of_two(names,preferred_groupmate,constraints,input_filename,output_filename)
elif button == 3:
start = time.time()
run_beta_groups_of_four(names, preferred_groupmate,constraints,input_filename,output_filename)
end = time.time()
print("TOTAL TIME ELAPSED IS: "+str(end-start))
messagebox.showerror("Work in progress!","I'm working on how to do this.",detail="Hopefully should be done in a couple of days.")
elif button == 4:
if(len(constraints)!=5):
messagebox.showerror("Work in progress!","Currently all five preferences are needed for groups of indeterminate sizes.",detail="Hopefully should be done in a couple of days.")
else:
run_indeterminate_groups(names,preferred_groupmate,constraints,max_groups,input_filename,output_filename)
except Exception as e:
messagebox.showerror("Oh No!",e,detail=traceback.format_exc())
processingWindow.destroy()
result = messagebox.askyesno("It's done.", "Finally!", detail="Do you want to close the tool?")
if result == True:
root.destroy()
##### Graphic User Interface ############################
## #
## This uses TkInter to create a simple GUI. Pressing #
## the 'Submit' button leads to the above 'get_input' #
## function to run with specific options. #
## #
#########################################################
root = Tk()
root.title("ELM Team Formation Tool (v "+versionNumber+")")
f1 = Frame(root, relief=GROOVE, width=50,height=50,borderwidth=0)
f1.pack()
label1 = Label(f1,text = 'Raw Data File (example.csv)')
label1.pack(pady=5)
label1.config(justify = CENTER)
entryText = StringVar(value='Final_Sample_Data.csv')
fileName = Entry(f1, width = 40,textvariable=entryText)
fileName.pack(side=LEFT,pady=10)
button_explore = Button(f1,text = "Browse",
command = browseFiles,
bg='#aaa662').pack(side=RIGHT)
f = Frame(root, relief=GROOVE, width=50,height=50,borderwidth=2)
f.pack()
## Radio Buttons #############################################
v = IntVar(value=1)
Label(f,
text="How would you like the groups formed?",
justify = LEFT,
padx = 20).pack(pady=10)
Radiobutton(f,