def maxi(): #matrix = [[20, 16, 22, 18], # [25, 28, 15, 21], # [27, 20, 23, 26], # [24, 22, 23, 22]] f = open('newds.txt') n = int(f.readline()) matrix = [] for i in range(n): list1 = map(int, (f.readline()).split()) matrix.append(list1) cost_matrix = make_cost_matrix(matrix) m = Munkres() indexes = m.compute(cost_matrix) print_matrix(matrix, msg='Highest profits through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print('(%d, %d) -> %d' % (row, column, value)) print('total profit=%d' % total) start_time = time.clock() timex = time.clock() - start_time time2 = ("Time =", timex, "seconds") print(time2) #timex1 = string(timex) timetext = open('times2.txt', 'a+') timetext.write(str(timex)) main()
def KM_mapping(action, VEHICLES, request_selected, vehicle, current_time): # ????? ''' :param prob_weights: a_prob :return: matching final action,"indexes": ''' print('cal_profit begin') profit_matrix = cal_profit(VEHICLES, request_selected, vehicle, current_time) print('cal_profit end') action = action.reshape([1, VEHICLES_NUMS * REQUEST_NUMS]) action = np.apply_along_axis(lambda x: round(x[0], 2), 0, action) action_weights = action.reshape([VEHICLES_NUMS, REQUEST_NUMS]) km_matrix = profit_matrix * action_weights # km_weights = make_cost_matrix(km_matrix, lambda item: (maxsize - item) if item != 0 else DISALLOWED) km_weights = make_cost_matrix(km_matrix, lambda item: (400 - item)) m = Munkres() print('km begin') indexes = m.compute(km_weights) print('km_end') print_matrix(profit_matrix, msg='Highers profit through this matrix:') total = 0 temp_indexes = copy.deepcopy(indexes) for row, column in temp_indexes: value = profit_matrix[row][column] if value == 0: indexes.remove((row, column)) total += value return indexes, total # KM_mapping([])
def KM_mapping(action, REQUESTS, VEHICLES, request_selected, vehicle, current_time): # ????? ''' :param prob_weights: a_prob :return: matching final action,"indexes": ''' # prob_weights = [5, DISALLOWED, 70, 0, # 10, 3, 2, 3, # 9, DISALLOWED, 4, 5, # 1,2,3,4, # 90,5,1,DISALLOWED] profit_matrix = cal_profit(REQUESTS, VEHICLES, request_selected, vehicle, current_time) km_matrix = profit_matrix * action.reshape([VEHICLES_NUMS, REQUEST_NUMS]) km_weights = make_cost_matrix( km_matrix, lambda item: (maxsize - item) if item != 0 else DISALLOWED) # matrix = np.array(prob_weights) # matrix = np.reshape(matrix, [VEHICLES_NUMS, REQUEST_NUMS]) # matrix = matrix.transpose() # cost_matrix = make_cost_matrix(matrix, lambda cost: (maxsize - cost) if (cost != DISALLOWED) else DISALLOWED) m = Munkres() indexes = m.compute(km_weights) print_matrix(profit_matrix, msg='Highers profit through this matrix:') total = 0 for row, column in indexes: # print(row, column) value = profit_matrix[row][column] total += value # print('(%d, %d) -> %d' % (row, column, value)) # print('total profit: %d' % total) return indexes, total # KM_mapping([])
def munkres_algorithm_indices_kl(cov1, cov2, verbose=True): """ Returns the optimal permutation of the states of the first sequence so as to best match the states of the second sequence on the basis of maximal overlaps of activated state sequences (ensure seq1 and seq2 are one-hot). Uses the Munkres/Hungarian algorithm. For details, see: https://en.wikipedia.org/wiki/Hungarian_algorithm https://pypi.org/project/munkres/ for usage of Munkres package """ from munkres import Munkres, print_matrix m = Munkres() # Similarity: high = good, Cost: low = good. # Solution: Cost = KL Divergence kl = np.array([[ kl_divergence(np.zeros(cov1.shape[1]), cov1[j, :, :], np.zeros(cov1.shape[1]), cov2[i, :, :]) for i in range(cov1.shape[0]) ] for j in range(cov1.shape[0])]) cost_matrix = kl indexes = m.compute(cost_matrix) if verbose: print('Cost matrix:\n') print(cost_matrix) print_matrix(cost_matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = cost_matrix[row][column] total += value if verbose: print('({}, {}) -> {}'.format(row, column, value)) print('total cost: {}'.format(total)) return np.array(indexes)[:, 1]
def get_matrix(y_pred, y_true): cm_array = confusion_matrix(y_pred, y_true) # print("matrix: ", cm_array) cm_array_new = [[0 for i in range(cluster_number)] for i in range(cluster_number)] for row in range(len(cm_array[:][0])): for col in range(len(cm_array[0][:])): cm_array_new[row][col] = cm_array[row][col] print("new_matrix: ", cm_array_new) # Calculating Profit, Rather than Cost cost_matrix = [] for row in cm_array_new: cost_row = [] for col in row: cost_row += [sys.maxsize - col] cost_matrix += [cost_row] m = Munkres() indexes = m.compute(cost_matrix) print_matrix(cm_array_new, msg='Highest profit through this matrix:') total = 0 prediction = [] for row, column in indexes: value = cm_array_new[row][column] prediction.append(column) total += value print('(%d, %d) -> %d' % (row, column, value)) print('total profit=%d' % total) return prediction
def printResult(indexes): print_matrix(matrix, msg="Optimal allocation of lunches to engineers for this matrix:") print "is:" total = 0 for row, column in indexes: value = matrix[row][column] total += value print "Engineer %d chooses Lunch %d with Enjoyment %d" % (row, column, value) print "Total enjoyment is %d" % total
def teest(): matrix = [[5, 9, 1], [10, 3, 2], [8, 7, 4]] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value return total
def mrCost(matrix): m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print('(%d, %d) -> %d' % (row, column, value)) print('total cost: %d' % total)
def rapid(matrix): m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total cost: %d' % total
def print_balanced_matrix(self, matrix, msg): (a, b) = matrix.shape if a > b: padding = ((0, 0), (0, a - b)) else: padding = ((0, b - a), (0, 0)) balanced_matrix = np.pad(matrix, padding, mode='constant', constant_values=0) print_matrix(balanced_matrix, msg=msg)
def calcuCost( matrix_partim): m = Munkres() indexes = m.compute(matrix_partim) print_matrix(matrix_partim, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix_partim[row][column] total += value print(row, column, total) print(total) return total
def swarm_algo(total_bots, bot_mat): m = Munkres() matrix = bot_mat indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total cost: %d' % total return
def calc(input_matrix): m = Munkres() indexes = m.compute(input_matrix) print_matrix(input_matrix, msg='Lowest cost through this matrix:') total = 0 print_matrix(indexes, msg='indexes:') for row, column in indexes: value = input_matrix[row][column] total += value print(f'({row}, {column}) -> {value}') print(f'total cost: {total}') return indexes
def test(): from munkres import Munkres, print_matrix matrix = loadData() m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total cost: %d' % total
def schedule_semester_students(semester, students): # make sure none of the students are already giving a talk. dss_students = [] for s in students: if Talk.objects.filter(event__semester=semester, student=s).exists(): continue dss_students.append(s) events = Event.objects.filter(event_type='DSS', semester=semester) schedulable = [] for e in events: # make an entry for every available slot. for copy in range(len(e.talks.all()), TALKS_PER_EVENT): schedulable.append(e) if len(dss_students) == 0 or len(schedulable) == 0: return # build up a preference matrix. cost_matrix = [] # the first index is for students for s in dss_students: costs = [] for e in schedulable: try: pref = TalkPreference.objects.get(student=s, event=e) pref = pref.preference except TalkPreference.DoesNotExist: pref = None costs.append(PREFERENCE_TO_COST[pref]) cost_matrix.append(costs) m = Munkres() indexes = m.compute(cost_matrix) print_matrix(cost_matrix) for row, column in indexes: if cost_matrix[row][column] == PREFERENCE_TO_COST['cannot']: continue print "Scheduling student", dss_students[row], "for talk on", schedulable[column].timestamp talk = Talk(student=dss_students[row], order=1) talk.save() schedulable[column].talks.add(talk) schedulable[column].save()
def mrProfit(matrix): cost_matrix = [] for row in matrix: cost_row = [] for col in row: cost_row += [sys.maxsize - col] cost_matrix += [cost_row] m = Munkres() indexes = m.compute(cost_matrix) print_matrix(matrix, msg='Highest profit through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print ('(%d, %d) -> %d' % (row, column, value)) print ('total profit=%d' % total)
def mrProfit(matrix): cost_matrix = [] for row in matrix: cost_row = [] for col in row: cost_row += [sys.maxsize - col] cost_matrix += [cost_row] m = Munkres() indexes = m.compute(cost_matrix) print_matrix(matrix, msg='Highest profit through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print('(%d, %d) -> %d' % (row, column, value)) print('total profit=%d' % total)
def munkres_algorithm_indices(seq1, seq2, verbose=True): """ Returns the optimal permutation of the states of the first sequence so as to best match the states of the second sequence on the basis of maximal overlaps of activated state sequences (ensure seq1 and seq2 are one-hot). Uses the Munkres/Hungarian algorithm. For details, see: https://en.wikipedia.org/wiki/Hungarian_algorithm https://pypi.org/project/munkres/ for usage of Munkres package """ from munkres import Munkres, print_matrix m = Munkres() def similarity_matrix(seq1, seq2): """ Calculates the similarity matrix of two active state sequences (where the sequences themselves are one-hot). For use with the Munkres/Hungarian algorithm. Rows correspond to seq1, columns to seq2, e.g. sim_mat[0, 1] would refer to 0th state of seq1 and 1st state of seq2 """ return np.array([[ dice_binary(seq1[:, j, np.newaxis], seq2[:, i, np.newaxis]) for i in range(seq2.shape[1]) ] for j in range(seq1.shape[1])]) # Similarity: high = good, Cost: low = good. # Solution: Cost = Similarity * -1 cost_matrix = -similarity_matrix(seq1, seq2) indexes = m.compute(cost_matrix) if verbose: print('Cost matrix:\n') print(cost_matrix) print_matrix(cost_matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = cost_matrix[row][column] total += value if verbose: print('({}, {}) -> {}'.format(row, column, value)) print('total cost: {}'.format(total)) return np.array(indexes)[:, 1]
def assign( matrix ): cost_matrix = [] for row in matrix: cost_row = [] for col in row: cost_row += [sys.maxint - col] cost_matrix += [cost_row] m = Munkres() indexes = m.compute(cost_matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total profit=%d' % total
def hungarian_al(): from munkres import Munkres, print_matrix matrix = [[5, 9, 1], [10, 3, 2], [8, 7, 4], [1, 2, 3]] matrix = np.random.random((278, 20)) matrix = matrix.tolist() print(matrix) # matrix = [[5,10,8,1], # [9,3,7,2], # [1,2,4,3]] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print(f'({row}, {column}) -> {value}') print(f'total cost: {total}')
def print_info(cls): """Print EasyMunk profit & cost matrices, along with Munkres chosen indexes and total cost & profit.""" print("____") if cls.last_profit_matrix: print("\nProfit Matrix: ") munkres.print_matrix(cls.last_profit_matrix) if cls.last_cost_matrix: print("\nCost Matrix: ") munkres.print_matrix(cls.last_cost_matrix) else: print("No info to print.") if cls.last_chosen_indexes: print("\nSelected Match Indexes: ") print("(primary index, secondary index)") print(cls.last_chosen_indexes) if cls.last_total_cost is not None: print("\nTotal Cost: " + str(cls.last_total_cost)) if cls.last_total_profit is not None: print("Total Profit: " + str(cls.last_total_profit)) print("____")
def hungarian(valu_mat, str): global counter global L global A global M global e global flag global available_vertex global V_matrix global temp cost_matrix = make_cost_matrix(valu_mat, lambda cost: sys.maxint - cost) m = Munkres() indexes = m.compute(cost_matrix) print_matrix(valu_mat, msg=str) total = 0 for row, column in indexes: value = valu_mat[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) M.append((row, column)) print 'total profit=%d' % total
def mini(): #matrix = [[20, 16, 22, 18], # [25, 28, 15, 21], # [27, 20, 23, 26], # [24, 22, 23, 22]] #matrix = [[20, 60, 50, 55, 67, 78, 89, 87, 90, 89], # [], # [], # [], # [], # [], # [], # [], # [], # [],] f = open('newds.txt') n = int(f.readline()) matrix = [] for i in range(n): list1 = map(int, (f.readline()).split()) matrix.append(list1) #matrix = [] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print('(%d, %d) -> %d' % (row, column, value)) print('total cost: %d' % total) start_time = time.clock() timex = time.clock() - start_time time2 = ("Time =", timex, "seconds") print(time2) #timex1 = string(timex) timetext = open('times2.txt', 'w') timetext.write(str(timex)) main()
def generate_matrix(colorPalette1, colorPalette2): len1=len(colorPalette1) len2=len(colorPalette2) matrix=[] if len1>=len2: for i in range(0, len1): matrix.append([]) for j in range(0,len1): for k in range(0,len1): matrix[j].append(100000) for i in range(0, len1): for j in range(0,len2): matrix[j][i]=int(round(color_distance(colorPalette1[i][0],colorPalette2[j][0])*10))+1 m = Munkres() indexes = m.compute(matrix) print indexes print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = (colorPalette1[row][1]+colorPalette2[column][1])/float(matrix[row][column])*1000000 total += value print '(%d, %d) -> %d' % (row, column, value) print 'total cost: %d' % total
def generate_matrix(self, utility_func): """ Generates a profit matrix based on a utility function that is used to calculate the profit of assigning each task to each units. Profit matrix is made balanced but nr of dummy row/cols are saved to be removed later :param utility_func: Function that takes parameters :unit and :task and returns a profit (int) of assigning a task to a unit :return: NxN profit matrix. Profit from unit X assigned to task Y. """ n_units = len(self.units) n_tasks = len(self.tasks) max_n = max(n_units, n_tasks) # Save nr dummy row/cols to remove later self.original_matrix_rows = n_units self.original_matrix_cols = n_tasks self.is_balanced = (n_units == n_tasks) self.matrix = np.zeros((max_n, max_n)) # This way balanced matrix is balanced right away for i in range(len(self.units)): for j in range(len(self.tasks)): self.matrix[i][j] = utility_func(self.units[i], self.tasks[j]) if self.debug: print_matrix(self.matrix, msg='\nmatrix generated from utility function')
def run_test(self): """ Runs anton's implementation of the hungarian algorithm and compares the results to the results of the imported munkres module. The munkres module will balance the problem automatically. Anton's implementation has it's own balancing function. Assignments can differ between the two algorithms, but the total the number of assignments and total profit should always be equal. """ test_matrices = self.matrices + self.rectangular_matrices for index, matrix in enumerate(test_matrices, start=1): print("\n\n----- TEST %d ------ " % (index)) print_matrix(matrix, msg='Original matrix:') self.print_balanced_matrix(matrix, msg='\nBalanced matrix:') print("\nAnton's assignments:") self.h.compute_assignments(matrix) self.h.pretty_print_assignments() print("Correct assignments:") valid_assignments = self.compute_test_assignments( matrix) # will balance matrices using munkres module valid_profit = self.pretty_print_assignments( valid_assignments, matrix) assert self.h.total_profit == valid_profit # make sure total profit is correct assert len(self.h.matching) == len( valid_assignments ) # make sure that dummy row/columns have been removed
def expand(mat1,duplic): duplic1 = duplic.tolist() mat2= mat1.repeat(duplic1[0],axis=0).repeat(duplic1[1],axis=1).tolist() m = Munkres() indexes = m.compute(mat2) print_matrix(mat2, msg='Lowest cost through this matrix:') total = 0 old_row = duplic[0].cumsum()-1 old_col = duplic[1].cumsum()-1 for row, column in indexes: value = mat2[row][column] total += value print 'new (%d, %d) is old (%d, %d) -> %d' % (row, column, old_row.searchsorted(row), old_col.searchsorted(column), value) print 'total cost: %d' % total n = Munkres() indexesn = n.compute(mat1) print 'au debut on avait :' for row, column in indexesn: value = mat1[row][column] total += value print '(%d, %d) -> %d' % (row, column, value)
connections = list(map(int, line.split(','))) vertices = [] if i == 0: base = connections for j in range(0, len(connections)): if float(int(connections[j])) == 0 or i == 0: vertices.append(999999) else: vertices.append(abs(flight_departures[j] - flight_arrivals[i])) connection_graph.append(vertices) i += 1 m = Munkres() paths = [] indexes = m.compute(connection_graph) print_matrix(connection_graph, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = connection_graph[row][column] total += value print('(%d, %d) -> %d' % (row, column, value)) new_path = True for path in paths: if row in path: path.append(column) new_path = False continue if new_path: path = [row, column] paths.append(path)
v = matrix[row][col] sum += v print('(%d, %d) -> %d' % (row + 1, col + 1, v)) print('Minimal Cost = %d' % sum) return idx, sum def KuhnMunkres_Max(matrix): '''highest profit assignment''' inf, tmp = 0x3f3f3f3f, [] for row in matrix: tmp_row = [] for col in row: tmp_row.append(inf - col) tmp.append(tmp_row) m, sum = Munkres(), 0 idx = m.compute(tmp) for row, col in idx: v = matrix[row][col] sum += v print('(%d, %d) -> %d' % (row, col, v)) print('Maximal Profit = %d' % sum) return idx, sum if __name__ == '__main__': a = [[5, 9, 1], [10, 3, 2], [8, 7, 4]] print_matrix(a) KuhnMunkres(a) KuhnMunkres_Max(a)
from munkres import Munkres, print_matrix matrix = [[1, 2, 3, 4], [4, 3, 2, 1], [4, 3, 1, 2], [1, 4, 3, 2]] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print ('(%d, %d) -> %d' % (row, column, value)) print ('total cost: %d' % total)
w = len(matrix_pd.columns) h = len(matrix_pd.index) print('Изначальная ширина - ' + str(w) + ' и Высота - ' + str(h)) for i in range(w - h): matrix_pd.loc['Empty slot ' + str(i)] = 0 for j in range(h - w): matrix_pd['Empty slot ' + str(j)] = 0 matrix_np = matrix_pd.values print('''------------------------------------ Исходная матрица''') print_matrix(matrix_np) print('''------------------------------------ Переворачиваем матрицу''') max = np.max(matrix_np) matrix_np = np.array(list(map(lambda el: max - el, matrix_np))) m = Munkres() print_matrix(matrix_np) print('''------------------------------------ Производим венгерский флекс''') index = m.compute(matrix_np) total = 0
def schedule_semester_judges(semester): # get all the events this semester. all_events = Event.objects.filter(event_type='DSS', semester=semester) schedulable = [] for e in all_events: for copy in range(len(e.judges.all()), JUDGES_PER_EVENT): schedulable.append(e) # get all the faculty. all_faculty = Advisor.objects.filter(active=True) if len(all_faculty) == 0 or len(schedulable) == 0: return # the goal is to schedule 3 judges per event, such that: # 1. if a judge is scheduled for an event, at least one of their students # said that they were available that day. # 2. none of that judge's students are presenting that day. # this function will assign one faculty member to one event, if possible. So, # hopefully the judges will be spread out as we call this function a few times. # find out which faculty are available for which events. for a in all_faculty: students = a.student_set.all() a.available = {} for e in all_events: if a in e.judges.all(): # the judge is already going to this event. a.available[e] = False continue a.available[e] = False for s in students: # if the student is inactive or exempt, don't worry about them. if not s.active or exemption_status(s).reason != "Not Exempted": continue # if one of the faculty's students are presenting, the judge is ineligible. student_talking = e.talks.all().filter(student=s).exists() if student_talking: a.available[e] = False break try: pref = TalkPreference.objects.get(student=s, event=e) pref = pref.preference except TalkPreference.DoesNotExist: pref = None # if any of the faculty's students are available, then they have # checked that their advisor is available as well. if pref != 'cannot': a.available[e] = True # build up a preference matrix. cost_matrix = [] # the first index is for faculty. for a in all_faculty: costs = [] for e in schedulable: available = a.available[e] costs.append(JUDGE_COST[available]) cost_matrix.append(costs) m = Munkres() indexes = m.compute(cost_matrix) print_matrix(cost_matrix) for row, column in indexes: print "Scheduling judge", all_faculty[row], "for talk on", schedulable[column].timestamp event = schedulable[column] event.judges.add(all_faculty[row]) event.save()
munkres = Munkres() G = [ [241, 83, 101, 281, 287], [209, 290, 235, 161, 135], [141, 180, 64, 309, 270], [153, 90, 251, 166, 182], [286, 251, 148, 215, 195], ] # for i in range(0, len(G)): # G[i] = [float(x * 0.001) for x in G[i]] print() print() print_matrix(G, msg="G:") print() print() result = munkres.compute(G) rows = list(sorted([item[0] for item in result])) cols = list(sorted([item[1] for item in result])) print("G result: ", result) print("rows:", rows) print("cols:", cols) # count = 50 # matrix = [] # #
""" By Chiegang Sape 02-03-2020 03:18 """ from munkres import Munkres, print_matrix matrix = [[10, 15, 13], [5, 14, 16], [11, 13, 14]] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix) print('resultat=', indexes) print('coût=', sum([matrix[i[0]][i[1]] for i in indexes]))
f.write('%d,%d,%d\n' % (person,obj,randnum)) temp.append(randnum+1) matrix.append(temp) #print matrix f.close() cost_matrix = [] for row in matrix: cost_row=[] for col in row: cost_row+=[sys.maxsize- col] cost_matrix += [cost_row] m = Munkres() indexes = m.compute(cost_matrix) print_matrix(matrix, msg='Highest profit through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value #print '(%d, %d) -> %d' % (row, column, value) print 'total profit=%d' % (total-N) end = time.time() print(end-start)
#!/usr/bin/env python import sys from munkres import Munkres, print_matrix, make_cost_matrix matrix = [[5, 9, 1], [10, 3, 2], [8, 7, 4]] cost_matrix = make_cost_matrix(matrix, lambda cost: sys.maxsize - cost) m = Munkres() indexes = m.compute(cost_matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total profit=%d' % total
if choice1 == 2: mat00 = input("Enter number: ") mat10 = input("Enter number: ") mat20 = input("Enter number: ") mat01 = input("Enter number: ") mat11 = input("Enter number: ") mat21 = input("Enter number: ") mat02 = input("Enter number: ") mat12 = input("Enter number: ") mat22 = input("Enter number: ") matrix = [[mat00, mat01, mat02], [mat10, mat11, mat12], [mat20, mat21, mat22]] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print('(%d, %d) -> %d' % (row, column, value)) print('total cost: %d' % total) elif choice1 == 2: mat00 = input("Enter number: ") mat10 = input("Enter number: ") mat20 = input("Enter number: ") mat01 = input("Enter number: ") mat11 = input("Enter number: ") mat21 = input("Enter number: ") mat02 = input("Enter number: ") mat12 = input("Enter number: ")
[ 973, 965, 905, 919, 133, 673, 665, 235, 509 ,613 ,673 ,815 ,165 ,992 ,326], [ 322, 148, 972, 962, 286, 255, 941, 541, 265 ,323 ,925 ,281 ,601 , 95 ,973], [ 445, 721, 11, 525, 473, 65, 511, 164, 138 ,672 , 18 ,428 ,154 ,448 ,848], [ 414, 456, 310, 312, 798, 104, 566, 520, 302 ,248 ,694 ,976 ,430 ,392 ,198], [ 184, 829, 373, 181, 631, 101, 969, 613, 840 ,740 ,778 ,458 ,284 ,760 ,390], [ 821, 461, 843, 513, 17, 901, 711, 993, 293 ,157 ,274 , 94 ,192 ,156 ,574], [ 34, 124, 4, 878, 450, 476, 712, 914, 838 ,669 ,875 ,299 ,823 ,329 ,699], [ 815, 559, 813, 459, 522, 788, 168, 586, 966 ,232 ,308 ,833 ,251 ,631 ,107], [ 813, 883, 451, 509, 615, 77, 281, 613, 459 ,205 ,380 ,274 ,302 , 35 ,805]] cost_matrix = [] for row in matrix: cost_row = [] for entry in row: cost_row += [1000 - entry] cost_matrix += [cost_row] m = Munkres() indexes = m.compute(cost_matrix) print_matrix(cost_matrix, msg='Highest profit through this matrix:') total = 0 print indexes for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total profit=%d' % total
def main(): BANNER = ''' ████████╗██╗ ██╗███████╗ ╚══██╔══╝██║ ██║██╔════╝ ██║ ███████║█████╗ ██║ ██╔══██║██╔══╝ ██║ ██║ ██║███████╗ ╚═╝ ╚═╝ ╚═╝╚══════╝ -v1.0 by @amirootyet █████╗ ██╗ ██╗ ██████╗ ██████╗ █████╗ ████████╗ ██████╗ ██████╗ ██╔══██╗██║ ██║ ██╔═══██╗██╔════╝██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗ ███████║██║ ██║ ██║ ██║██║ ███████║ ██║ ██║ ██║██████╔╝ ██╔══██║██║ ██║ ██║ ██║██║ ██╔══██║ ██║ ██║ ██║██╔══██╗ ██║ ██║███████╗███████╗╚██████╔╝╚██████╗██║ ██║ ██║ ╚██████╔╝██║ ██║ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═ ''' print(BANNER) ######################################## # Arguments to the command-line utility parser = argparse.ArgumentParser( description='A utility to manage CSE 231 TA assignment with the Munkres algorithm.') parser.add_argument("-a", "--assign", help='Find optimal (miminum cost) TA assignments.', action='store_true') parser.add_argument("-b", "--busybees", help="Find TAs that have a conflict for more than half" "of the total work slots.", action='store_true') parser.add_argument("-f", "--filename", required=True, help="CSV file containing TA preferences.") parser.add_argument("-c", "--costmatrix", help="Build and display the TA cost matrix.", action='store_true') args = parser.parse_args() ######################################### fp = open_file(args.filename) # Attempt to open the CSV file with TA preferences. time_slots, preference_dictionary = assistants_and_slots(fp) # Read time slots and preferences assistants = list(preference_dictionary.keys()) # Create a list of available TAs # Show the "busy bees"; these TAs make optimal assignment challenging. if args.busybees: busy_bees = [] for assistant, costs in preference_dictionary.items(): conflicts = costs.count(COSTS['Conflict']) # Count the conflicts for each TA. if conflicts > (len(costs)) / 2: # If the TA has more conflicts than half of the total slots. busy_bees.append((assistant, conflicts)) print("-" * 40) print("{:<20} {} (/{})".format('Busy Bee', 'Conflicts', len(costs))) print("-" * 40) for busy_bee in busy_bees: print("{:<20} {}".format(busy_bee[0], busy_bee[1])) # Build and show the cost matrix. elif args.costmatrix: cost_matrix = build_cost_matrix(preference_dictionary) # Build the cost matrix. print_matrix(cost_matrix) # Display the cost matrix. # Assign TAs the time slots / labs. elif args.assign: cost_matrix = build_cost_matrix(preference_dictionary) munkres_obj = Munkres() total = 0 indexes = munkres_obj.compute(cost_matrix) # This is where the assignment magic happens. print('{:<17s} | {:<25s} -> {:<4s}'.format('TAs', 'Assignment', 'Cost')) print("-" * 55) for row, col in indexes: cost = cost_matrix[row][col] total += cost # Calculate total cost of assignment. print('{:<17s} | {:<25s} -> {:<4d}'.format(assistants[row], time_slots[col], cost)) # Display the assignment result. for k, v in COSTS.items(): print(str(k) + " = " + str(v), end="; ") print("\nTimeslots: {}; TAs: {}".format(len(time_slots), len(assistants))) else: print("Nothing to do. See --help") fp.close() # Close the CSV file before exit.