|
| 1 | +# An example of solving the Generalized Assignment Problem (GAP) using highspy |
| 2 | +# Also demonstrates how to use callbacks to print cuts as they are found |
| 3 | +from highspy import * |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +# |
| 7 | +# GAP instances can be taken from: |
| 8 | +# http://people.brunel.ac.uk/~mastjjb/jeb/orlib/gapinfo.html |
| 9 | +# |
| 10 | +# Expected format: |
| 11 | +# - number machines |
| 12 | +# _ number jobs |
| 13 | +# - cost of each job on each machine |
| 14 | +# - size of each job on each machine |
| 15 | +# - capacity of each machine |
| 16 | + |
| 17 | +input_data = ''' 5 15 |
| 18 | +17 21 22 18 24 15 20 18 19 18 16 22 24 24 16 |
| 19 | +23 16 21 16 17 16 19 25 18 21 17 15 25 17 24 |
| 20 | +16 20 16 25 24 16 17 19 19 18 20 16 17 21 24 |
| 21 | +19 19 22 22 20 16 19 17 21 19 25 23 25 25 25 |
| 22 | +18 19 15 15 21 25 16 16 23 15 22 17 19 22 24 |
| 23 | +8 15 14 23 8 16 8 25 9 17 25 15 10 8 24 |
| 24 | +15 7 23 22 11 11 12 10 17 16 7 16 10 18 22 |
| 25 | +21 20 6 22 24 10 24 9 21 14 11 14 11 19 16 |
| 26 | +20 11 8 14 9 5 6 19 19 7 6 6 13 9 18 |
| 27 | +8 13 13 13 10 20 25 16 16 17 10 10 5 12 23 |
| 28 | +36 34 38 27 33 |
| 29 | +'''.split() |
| 30 | + |
| 31 | +# read from file |
| 32 | +# with open(r"filename", 'r') as input_file: |
| 33 | +# input_data = input_file.read().split() |
| 34 | + |
| 35 | +# parse input |
| 36 | +M = int(input_data[0]) |
| 37 | +J = int(input_data[1]) |
| 38 | +idx = np.cumsum([2, M * J, M * J, M]) |
| 39 | +cost = np.array(input_data[idx[0]:idx[1]], dtype=np.float64).reshape((M, J)) |
| 40 | +size = np.array(input_data[idx[1]:idx[2]], dtype=np.float64).reshape((M, J)) |
| 41 | +capacity = np.array(input_data[idx[2]:idx[3]], dtype=np.float64) |
| 42 | + |
| 43 | +# build model |
| 44 | +model = Highs() |
| 45 | + |
| 46 | +X = model.addBinaries(M, J) |
| 47 | + |
| 48 | +# assign each job to exactly one machine |
| 49 | +model.addConstrs(X[:, j].sum() == 1 for j in range(J)) |
| 50 | + |
| 51 | +# each machine can only take jobs that fit |
| 52 | +model.addConstrs((size[m, :] * X[m, :]).sum() <= capacity[m] for m in range(M)) |
| 53 | + |
| 54 | +# print out the cuts as we solve |
| 55 | +def printCuts(e): |
| 56 | + for c in e.cuts: |
| 57 | + print(c) |
| 58 | + |
| 59 | +model.cbMipGetCutPool += printCuts |
| 60 | + |
| 61 | +# minimize total cost |
| 62 | +model.minimize((cost * X).sum()) |
| 63 | + |
| 64 | +# print out solution (i.e., which jobs are assigned to which machines) |
| 65 | +print(model.getObjectiveValue()) |
| 66 | + |
| 67 | +np.set_printoptions(formatter={'all': lambda x: str(x)}) |
| 68 | + |
| 69 | +for m in range(M): |
| 70 | + jobs_on_machine = np.nonzero(model.vals(X[m, :]) > 0)[0] |
| 71 | + print(jobs_on_machine) |
0 commit comments