Пример #1
0
def main(sol='GLPK'):

    # Create the solver.

    # using GLPK
    if sol == 'GLPK':
        solver = pywraplp.Solver('CoinsGridGLPK',
                                 pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)
    else:
        # Using CLP
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CLP_LINEAR_PROGRAMMING)

    # data
    # number of points
    num = 14

    # temperature
    t = [20, 30, 80, 125, 175, 225, 275, 325, 360, 420, 495, 540, 630, 700]

    # percentage gas
    F = [
        0.0, 5.8, 14.7, 31.6, 43.2, 58.3, 78.4, 89.4, 96.4, 99.1, 99.5, 99.9,
        100.0, 100.0
    ]

    p = 4

    #
    # declare variables
    #
    a = [solver.NumVar(-100, 100, 'a[%i]' % i) for i in range(p + 1)]

    # to minimize
    z = solver.Sum([(F[i] - (sum([a[j] * t[i]**j for j in range(p + 1)])))
                    for i in range(num)])

    #
    # constraints
    #
    solver.Add(solver.Sum([20**i * a[i] for i in range(p + 1)]) == 0)

    solver.Add((a[0] + sum([700.0**j * a[j]
                            for j in range(1, p + 1)])) == 100.0)

    for i in range(num):
        solver.Add(
            solver.Sum([j * a[j] * t[i]**(j - 1) for j in range(p + 1)]) >= 0)

    objective = solver.Minimize(z)

    solver.Solve()

    print
    print 'z = ', solver.ObjectiveValue()
    for i in range(p + 1):
        print a[i].SolutionValue(),
    print
Пример #2
0
def main():
    t = 'k out of n'
    n = 12
    seed(100)
    bound = [randint(5, 15) for _ in range(n)]
    tableutils.printmat([['Max sum of'] + bound])
    for k in range(1, n + 1):
        s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
        x = [s.NumVar(0, bound[i], '') for i in range(n)]
        y = [s.NumVar(0, bound[i], '') for i in range(n)]
        Costx = sum(x[i] for i in range(n))
        Costy = sum(y[i] for i in range(n))
        s.Maximize(Costx + Costy)
        k_out_of_n(s, k, x, '==')
        ldg = sosn(s, k, y)
        rc = s.Solve()
        if rc != 0:
            print 'Error', rc
        sy = SolVal(y)
        sx = SolVal(x)
        yy = [[' ', 'x'][e > 0] for e in sy]
        xx = [[' ', 'x'][e > 0] for e in sx]

        tableutils.printmat(
            tableutils.wrapmat(
                [xx, yy],
                ['{0}/{1}'.format(k, n), 'Adjacent {0}/{1}'.format(k, n)],
                None), 0, False)
    return rc
Пример #3
0
def main(unused_argv):

  # Create the solver.

  # using GLPK
  solver = pywraplp.Solver('CoinsGridGLPK',
                          pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)

  # Using CLP
  # solver = pywraplp.Solver('CoinsGridCLP',
  #                          pywraplp.Solver.CLP_LINEAR_PROGRAMMING)


  # data
  num_products = 2

  products = ['Gas', 'Chloride']
  components = ['nitrogen', 'hydrogen', 'chlorine']

  demand = [ [1,3,0], [1,4,1]]
  profit = [30,40]
  stock = [50,180,40]

  # declare variables
  production = [solver.NumVar(0, 100000, 'production[%i]' % i )
                for i in range(num_products)]

  #
  # constraints
  #
  for c in range(len(components)):
    solver.Add(solver.Sum([demand[p][c]*production[p]
                           for p in range(len(products)) ]) <= stock[c])


  # objective
  # Note: there is no support for solver.ScalProd in the LP/IP interface
  objective = solver.Maximize(solver.Sum([production[p]*profit[p]
                                          for p in range(num_products)]))


  print 'NumConstraints:', solver.NumConstraints()
  print 'NumVariables:', solver.NumVariables()
  print

  #
  # solution and search
  #
  solver.Solve()

  print
  print 'objective = ', solver.ObjectiveValue()
  for i in range(num_products):
      print products[i], '=', production[i].SolutionValue(),
      print 'ReducedCost = ', production[i].ReducedCost()

  print
  print 'walltime  :', solver.WallTime(), 'ms'
  print 'iterations:', solver.Iterations()
def main():
    bounds = []
    s = pywraplp.Solver('', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)
    a = [1, 2]
    x = [s.NumVar(3, 5, 'x[%i]' % i) for i in range(2)]
    b = 10
    bounds = bounds_on_box(a, x, b)
    print bounds == [-1, 5]
Пример #5
0
def main():
    bounds = []
    s = pywraplp.Solver('',pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    a = [[2],[-2]]
    b = [3,-12]
    x = s.NumVar(2,5,'x')
    z,l = maximax(s,a,[x],b) 
    rc = s.Solve()
    print 'x = ',SolVal(x)
    print 'z = ',SolVal(z)
    print '\delta = ', SolVal(l)
def bounds_on_box(a, x, b):
    Bounds, n = [None, None], len(a)
    s = pywraplp.Solver('Box', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)
    xx = [s.NumVar(x[i].Lb(), x[i].Ub(), '') for i in range(n)]
    S = s.Sum([-b] + [a[i] * xx[i] for i in range(n)])
    s.Maximize(S)
    rc = s.Solve()
    Bounds[1] = None if rc != 0 else ObjVal(s)
    s.Minimize(S)
    s.Solve()
    Bounds[0] = None if rc != 0 else ObjVal(s)
    return Bounds
Пример #7
0
def solve_bacteria():
  t = 'Bacterial coexistence'
  s = pywraplp.Solver(t,pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) 
  x = [s.NumVar(0, 1000,'x[%i]' % i) for i in range(3)]       
  pop = s.NumVar(0,3000,'pop') 
  s.Add(2*x[0] + x[1] + x[2] <= 1500)                           
  s.Add(x[0] + 3*x[1] + 2*x[2] <= 3000)                          
  s.Add(x[0] + 2*x[1] + 3*x[2] <= 4000)                          
  s.Add(pop == x[0] + x[1] + x[2]) 
  s.Maximize(pop)                                
  s.Solve() 
  return SolVal(pop),SolVal(x)
Пример #8
0
def solve_model(D, C=None):
    t = 'Set Packing'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    nbRosters = len(D)
    nbCrew = max([e for d in D for e in d]) + 1
    S = [s.IntVar(0, 1, '') for i in range(nbRosters)]
    for j in range(nbCrew):
        s.Add(1 >= sum(S[i] for i in range(nbRosters) if j in D[i]))
    s.Maximize(
        s.Sum(S[i] * (1 if C == None else C[i]) for i in range(nbRosters)))
    rc = s.Solve()
    Rosters = [i for i in range(nbRosters) if S[i].SolutionValue() > 0]
    return rc, s.Objective().Value(), Rosters
def minimize_piecewise_linear(Points,B,convex=True):
    t = 'Piecewise'
    s = pywraplp.Solver(t,pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    n = len(Points)
    x = s.NumVar(Points[0][0],Points[n-1][0],'x')
    l = [s.NumVar(0,1,'l[%i]' % (i,)) for i in range(n)]  
    s.Add(1 == sum(l[i] for i in range(n)))               
    d = sosn(s, 2, l)
    s.Add(x == sum(l[i]*Points[i][0] for i in range(n)))  
    s.Add(x >= B)                                                 
    Cost = s.Sum(l[i]*Points[i][1] for i in range(n))     
    s.Minimize(Cost)
    rc = s.Solve()
    return rc,SolVal(l),SolVal(d[1])
def solve_model_clp(D):
  t = 'Project management'
  s = pywraplp.Solver(t,pywraplp.Solver.CLP_LINEAR_PROGRAMMING)
  n = len(D)
  max = sum(D[i][1] for i in range(n))                           
  t = [s.NumVar(0,max,'t[%i]' % i) for i in range(n)]           
  Total = s.NumVar(0,max,'Total')                          
  for i in range(n):  
    s.Add(t[i]+D[i][1] <= Total)                   
    for j in D[i][2]:
      s.Add(t[j]+D[j][1] <= t[i])               
  s.Minimize(Total)
  rc = s.Solve()
  return rc, SolVal(Total),SolVal(t)
Пример #11
0
def solve_model(D, C=None):
    t = 'Set Cover'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    nbSup = len(D)
    nbParts = max([e for d in D for e in d]) + 1
    S = [s.IntVar(0, 1, '') for i in range(nbSup)]
    for j in range(nbParts):
        s.Add(1 <= sum(S[i] for i in range(nbSup) if j in D[i]))
    s.Minimize(s.Sum(S[i] * (1 if C is None else C[i]) for i in range(nbSup)))
    rc = s.Solve()
    Suppliers = [i for i in range(nbSup) if SolVal(S[i]) > 0]
    Parts = [[i for i in range(nbSup) if j in D[i] and SolVal(S[i]) > 0]
             for j in range(nbParts)]
    return rc, ObjVal(s), Suppliers, Parts
def solve_model(D, F):
    t = 'Facility location problem'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    m, n = len(D) - 1, len(D[0]) - 1
    x = [[s.NumVar(0, D[i][-1], '') for j in range(n)] for i in range(m)]
    y = [s.IntVar(0, 1, '') for i in range(m)]
    for i in range(m):
        s.Add(D[i][-1] * y[i] >= sum(x[i][j] for j in range(n)))
    for j in range(n):
        s.Add(D[-1][j] == sum(x[i][j] for i in range(m)))
    Fcost = s.Sum(y[i] * F[i] for i in range(m))
    Dcost = s.Sum(x[i][j] * D[i][j] for i in range(m) for j in range(n))
    s.Minimize(Dcost + Fcost)
    rc = s.Solve()
    return rc, ObjVal(s), SolVal(x), SolVal(y)
def solve_model(D):
    t = 'Power distribution problem'
    s = pywraplp.Solver(t, pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)
    m, n = len(D) - 1, len(D[0]) - 1
    B = sum([D[-1][j] for j in range(n)])
    G = [[s.NumVar(0,B if D[i][j] else 0,'') for j in range(n)] \
         for i in range(m)]
    for i in range(m):
        s.Add(D[i][-1] >= sum(G[i][j] for j in range(n)))
    for j in range(n):
        s.Add(D[-1][j] == sum(G[i][j] for i in range(m)))
    Cost = s.Sum(G[i][j] * D[i][j] for i in range(m) for j in range(n))
    s.Minimize(Cost)
    rc = s.Solve()
    return rc, ObjVal(s), SolVal(G)
Пример #14
0
def main(unused_argv):

    # Create the solver.

    # using GLPK
    solver = pywraplp.Solver('CoinsGridGLPK',
                             pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)

    # Using CLP
    # solver = pywraplp.Solver('CoinsGridCLP',
    #                          pywraplp.Solver.CLP_LINEAR_PROGRAMMING)

    # data
    num_products = 2
    Gas = 0
    Chloride = 1

    products = ['Gas', 'Chloride']

    # declare variables
    production = [
        solver.NumVar(0, 100000, 'production[%i]' % i)
        for i in range(num_products)
    ]

    #
    # constraints
    #
    solver.Add(production[Gas] + production[Chloride] <= 50)
    solver.Add(3 * production[Gas] + 4 * production[Chloride] <= 180)

    # objective
    objective = solver.Maximize(40 * production[Gas] +
                                50 * production[Chloride])

    print 'NumConstraints:', solver.NumConstraints()

    #
    # solution and search
    #
    solver.Solve()

    print
    print 'objective = ', solver.ObjectiveValue()
    for i in range(num_products):
        print products[i], '=', production[i].SolutionValue(),
        print 'ReducedCost = ', production[i].ReducedCost()
Пример #15
0
def solve_model_eliminate(D, Subtours=[]):
    t = 'TSP'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    n = len(D)
    x = [[s.IntVar(0, 1, '') for j in range(n)] for i in range(n)]
    for i in range(n):
        s.Add(1 == sum(x[i][j] for j in range(n)))
        s.Add(1 == sum(x[j][i] for j in range(n)))
        s.Add(0 == x[i][i])
    for sub in Subtours:
        K = [x[sub[i]][sub[j]]+x[sub[j]][sub[i]]\
             for i in range(len(sub)-1) for j in range(i+1,len(sub))]
        s.Add(len(sub) - 1 >= sum(K))
    s.Minimize(s.Sum(x[i][j] * D[i][j] for i in range(n) for j in range(n)))
    rc = s.Solve()
    tours = extract_tours(SolVal(x), n)
    return rc, ObjVal(s), tours
Пример #16
0
def solve_model(M, nf, Q=None, P=None, no_part=False):
    t = 'Staffing'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    nbt, n, B = len(M) - 1, len(M[0]) - 1, sum(M[t][-1]
                                               for t in range(len(M) - 1))
    x = [s.IntVar(0, B, 'x[%i]' % i) for i in range(n)]
    for t in range(nbt):
        s.Add(sum([M[t][i] * x[i] for i in range(n)]) >= M[t][-1])
    if Q:
        for i in range(n):
            s.Add(x[i] >= Q[i])
    if P:
        s.Add(sum(x[i] for i in range(nf)) >= P)
    if no_part:
        for t in range(nbt):
            s.Add(B*sum([M[t][i] * x[i] for i in range(nf)]) \
                  >= sum([M[t][i] * x[i] for i in range(nf,n)]))
    s.Minimize(sum(x[i] * M[-1][i] for i in range(n)))
    rc = s.Solve()
    return rc, ObjVal(s), SolVal(x)
Пример #17
0
def main(unused_argv):
  
  # Create the solver.

  # using GLPK
  solver = pywraplp.Solver('CoinsGridGLPK',
                          pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)

  # Using CLP
  # solver = pywraplp.Solver('CoinsGridCLP',
  #                          pywraplp.Solver.CLP_LINEAR_PROGRAMMING)


  # data

  # declare variables
  Gas = solver.NumVar(0, 100000, 'Gas')
  Chloride = solver.NumVar(0, 100000, 'Cloride')

  #
  # constraints
  #
  solver.Add(Gas + Chloride <= 50)
  solver.Add(3 * Gas + 4 * Chloride <= 180)

  # objective
  objective = solver.Maximize(40 * Gas + 50 * Chloride)


  print 'NumConstraints:', solver.NumConstraints()


  #
  # solution and search
  #
  solver.Solve()

  print
  print 'objective = ', solver.ObjectiveValue()
  print 'Gas = ', Gas.SolutionValue(), 'ReducedCost =', Gas.ReducedCost()
  print 'Chloride:', Chloride.SolutionValue(), 'ReducedCost =', Chloride.ReducedCost()
Пример #18
0
def solve_model(D, W):
    t = 'Bin Packing'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    nbP = sum([P[0] for P in D])
    w = [
        e for sub in [[D[i][1]] * D[i][0] for i in range(len(D))] for e in sub
    ]
    nbT = bound_trucks(w, W)
    x = [[s.IntVar(0, 1, '') for j in range(nbT)] for i in range(nbP)]
    y = [s.IntVar(0, 1, '') for j in range(nbT)]
    for j in range(nbT):
        s.Add(sum(w[i] * x[i][j] for i in range(nbP)) <= W * y[j])
    for i in range(nbP):
        s.Add(sum([x[i][j] for j in range(nbT)]) >= 1)
    s.Minimize(s.Sum(y[j] for j in range(nbT)))
    rc = s.Solve()
    P2T = [(i, j) for i in range(nbP) for j in range(nbT)
           if x[i][j].SolutionValue() > 0]
    T2P = [[j, [(i,w[i]) for i in range(nbP) if x[i][j].SolutionValue()>0]] \
           for j in range(nbT)]
    return rc, s.Objective().Value(), P2T, T2P
Пример #19
0
def solve_model(C, D=None, Z=False):
    t = 'Multi-commodity mincost flow problem'
    s = pywraplp.Solver(t, pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
    K, n = len(C), len(C[0]) - 1,
    B = [sum(C[k][-1][j] for j in range(n)) for k in range(K)]
    x = [[[s.IntVar(0,B[k] if C[k][i][j] else 0,'') \
           if Z else s.NumVar(0,B[k] if C[k][i][j] else 0,'') \
           for j in range(n)] for i in range(n)] for k in range(K)]
    for k in range(K):
        for i in range(n):
            s.Add(C[k][i][-1] - C[k][-1][i] == sum(x[k][i][j]
                                                   for j in range(n)) -
                  sum(x[k][j][i] for j in range(n)))
    if D:
        for i in range(n):
            for j in range(n):
                s.Add(sum(x[k][i][j] for k in range(K)) <= \
                      D if type(D) in [int,float] else D[i][j])
    Cost = s.Sum(x[k][i][j]*C[k][i][j] \
                 for i in range(n) for j in range(n) for k in range(K))
    s.Minimize(Cost)
    rc = s.Solve()
    return rc, ObjVal(s), SolVal(x)
Пример #20
0
def newSolver(name, integer=False):
    return pywraplp.Solver(name,\
                           pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING \
                           if integer else \
                           pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)
Пример #21
0
def main(sol = 'GLPK'):

  # Create the solver.

  print 'Solver: ', sol

  # using GLPK
  if sol == 'GLPK':
    solver = pywraplp.Solver('CoinsGridGLPK',
                             pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
  else:
  # Using CLP
      solver = pywraplp.Solver('CoinsGridCLP',
                               pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)


  #
  # data
  #
  nb_items = 12
  nb_resources = 7
  items = range(nb_items)
  resources = range(nb_resources)

  capacity = [ 18209, 7692, 1333, 924, 26638, 61188, 13360 ]
  value = [ 96, 76, 56, 11, 86, 10, 66, 86, 83, 12, 9, 81 ]
  use = [[ 19,  1, 10, 1,   1, 14, 152, 11, 1,  1, 1, 1 ],
         [ 0,   4, 53, 0,   0, 80,   0, 4, 5,   0, 0, 0 ],
         [ 4, 660,  3, 0, 30,    0,  3, 0, 4, 90, 0, 0],
         [ 7,   0, 18, 6, 770, 330,  7, 0, 0,   6, 0, 0],
         [ 0, 20,   0, 4, 52,    3,  0, 0, 0,   5, 4, 0],
         [ 0,   0, 40, 70,  4, 63,   0, 0, 60,  0, 4, 0],
         [ 0, 32,   0, 0,   0,   5,  0, 3, 0, 660, 0, 9]]

  max_value = max(capacity)

  #
  # variables
  #
  take = [solver.IntVar(0, max_value, 'take[%i]' % j) for j in items]


  # total cost, to be maximized
  z = solver.Sum([value[i] * take[i] for i in items])

  #
  # constraints
  #
  for r in resources:
    solver.Add(solver.Sum([use[r][i] * take[i]
                           for i in items]) <= capacity[r])

  # objective
  objective = solver.Maximize(z)


  #
  # solution and search
  #
  solver.Solve()

  print
  print 'z: ', int(solver.ObjectiveValue())

  print 'take:',
  for i in items:
    print int(take[i].SolutionValue()),
  print


  print
  print 'walltime  :', solver.WallTime(), 'ms'
  if sol == 'CBC':
    print 'iterations:', solver.Iterations()
Пример #22
0
def main(sol='GLPK'):

    # Create the solver.

    # using GLPK
    if sol == 'GLPK':
        solver = pywraplp.Solver('CoinsGridGLPK',
                                 pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)
    else:
        # Using CLP
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CLP_LINEAR_PROGRAMMING)

    # data
    rows = 3
    cols = 3

    game = [[3.0, -1.0, -3.0], [-2.0, 4.0, -1.0], [-5.0, -6.0, 2.0]]

    #
    # declare variables
    #

    #
    # row player
    #
    x1 = [solver.NumVar(0, 1, 'x1[%i]' % i) for i in range(rows)]

    v = solver.NumVar(-2, 2, 'v')

    for i in range(rows):
        solver.Add(v - solver.Sum([x1[j] * game[j][i]
                                   for j in range(cols)]) <= 0)

    solver.Add(solver.Sum(x1) == 1)

    objective = solver.Maximize(v)

    solver.Solve()

    print
    print 'row player:'
    print 'v = ', solver.ObjectiveValue()
    print 'Strategies: '
    for i in range(rows):
        print x1[i].SolutionValue(),
    print
    print

    #
    # For column player:
    #
    x2 = [solver.NumVar(0, 1, 'x2[%i]' % i) for i in range(cols)]

    v2 = solver.NumVar(-2, 2, 'v2')

    for i in range(cols):
        solver.Add(v2 - solver.Sum([x2[j] * game[i][j]
                                    for j in range(rows)]) >= 0)

    solver.Add(solver.Sum(x2) == 1)

    objective = solver.Minimize(v2)

    solver.Solve()

    print
    print 'column player:'
    print 'v2 = ', solver.ObjectiveValue()
    print 'Strategies: '
    for i in range(rows):
        print x2[i].SolutionValue(),
    print

    print
    print 'walltime  :', solver.WallTime(), 'ms'
    print 'iterations:', solver.Iterations()
    print
Пример #23
0
def main(sol='GLPK'):

    # Create the solver.

    print 'Solver: ', sol

    # using GLPK
    if sol == 'GLPK':
        solver = pywraplp.Solver(
            'CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
    else:
        # Using CLP
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    #
    # data
    #
    # commodities
    num_commodities = 77
    C = range(num_commodities)

    #  days in a year
    days = 365.25

    # nutrients
    num_nutrients = 9
    N = range(num_nutrients)

    nutrients = [
        "calories",  # Calories, unit = 1000
        "protein",  # Protein, unit = grams
        "calcium",  # Calcium, unit = grams
        "iron",  # Iron, unit = milligrams
        "vitaminA",  # Vitamin A, unit = 1000 International Units
        "thiamine",  # Thiamine, Vit. B1, unit = milligrams
        "riboflavin",  # Riboflavin, Vit. B2, unit = milligrams
        "niacin",  # Niacin (Nicotinic Acid), unit = milligrams
        "ascorbicAcid"  # Ascorbic Acid, Vit. C, unit = milligrams
    ]

    commodities = [["Wheat Flour (Enriched)", "10 lb."], ["Macaroni", "1 lb."],
                   ["Wheat Cereal (Enriched)", "28 oz."],
                   ["Corn Flakes", "8 oz."], ["Corn Meal", "1 lb."],
                   ["Hominy Grits", "24 oz."], ["Rice", "1 lb."],
                   ["Rolled Oats",
                    "1 lb."], ["White Bread (Enriched)", "1 lb."],
                   ["Whole Wheat Bread", "1 lb."], ["Rye Bread", "1 lb."],
                   ["Pound Cake", "1 lb."], ["Soda Crackers", "1 lb."],
                   ["Milk", "1 qt."], ["Evaporated Milk (can)", "14.5 oz."],
                   ["Butter", "1 lb."], ["Oleomargarine", "1 lb."],
                   ["Eggs", "1 doz."], ["Cheese (Cheddar)", "1 lb."],
                   ["Cream", "1/2 pt."], ["Peanut Butter", "1 lb."],
                   ["Mayonnaise", "1/2 pt."], ["Crisco", "1 lb."],
                   ["Lard", "1 lb."], ["Sirloin Steak", "1 lb."],
                   ["Round Steak", "1 lb."], ["Rib Roast", "1 lb."],
                   ["Chuck Roast", "1 lb."], ["Plate", "1 lb."],
                   ["Liver (Beef)", "1 lb."], ["Leg of Lamb", "1 lb."],
                   ["Lamb Chops (Rib)", "1 lb."], ["Pork Chops", "1 lb."],
                   ["Pork Loin Roast", "1 lb."], ["Bacon", "1 lb."],
                   ["Ham - smoked", "1 lb."], ["Salt Pork", "1 lb."],
                   ["Roasting Chicken", "1 lb."], ["Veal Cutlets", "1 lb."],
                   ["Salmon, Pink (can)", "16 oz."], ["Apples", "1 lb."],
                   ["Bananas", "1 lb."], ["Lemons", "1 doz."],
                   ["Oranges", "1 doz."], ["Green Beans", "1 lb."],
                   ["Cabbage", "1 lb."], ["Carrots", "1 bunch"],
                   ["Celery", "1 stalk"], ["Lettuce", "1 head"],
                   ["Onions", "1 lb."], ["Potatoes", "15 lb."],
                   ["Spinach", "1 lb."], ["Sweet Potatoes", "1 lb."],
                   ["Peaches (can)",
                    "No. 2 1/2"], ["Pears (can)", "No. 2 1/2,"],
                   ["Pineapple (can)", "No. 2 1/2"],
                   ["Asparagus (can)", "No. 2"],
                   ["Grean Beans (can)", "No. 2"],
                   ["Pork and Beans (can)", "16 oz."], ["Corn (can)", "No. 2"],
                   ["Peas (can)", "No. 2"], ["Tomatoes (can)", "No. 2"],
                   ["Tomato Soup (can)", "10 1/2 oz."],
                   ["Peaches, Dried", "1 lb."], ["Prunes, Dried", "1 lb."],
                   ["Raisins, Dried", "15 oz."], ["Peas, Dried", "1 lb."],
                   ["Lima Beans, Dried", "1 lb."],
                   ["Navy Beans, Dried", "1 lb."], ["Coffee", "1 lb."],
                   ["Tea", "1/4 lb."], ["Cocoa", "8 oz."],
                   ["Chocolate", "8 oz."], ["Sugar", "10 lb."],
                   ["Corn Sirup", "24 oz."], ["Molasses", "18 oz."],
                   ["Strawberry Preserve", "1 lb."]]

    # price and weight are the two first columns
    data = [
        [36.0, 12600.0, 44.7, 1411.0, 2.0, 365.0, 0.0, 55.4, 33.3, 441.0, 0.0],
        [14.1, 3217.0, 11.6, 418.0, 0.7, 54.0, 0.0, 3.2, 1.9, 68.0, 0.0],
        [24.2, 3280.0, 11.8, 377.0, 14.4, 175.0, 0.0, 14.4, 8.8, 114.0, 0.0],
        [7.1, 3194.0, 11.4, 252.0, 0.1, 56.0, 0.0, 13.5, 2.3, 68.0, 0.0],
        [4.6, 9861.0, 36.0, 897.0, 1.7, 99.0, 30.9, 17.4, 7.9, 106.0, 0.0],
        [8.5, 8005.0, 28.6, 680.0, 0.8, 80.0, 0.0, 10.6, 1.6, 110.0, 0.0],
        [7.5, 6048.0, 21.2, 460.0, 0.6, 41.0, 0.0, 2.0, 4.8, 60.0, 0.0],
        [7.1, 6389.0, 25.3, 907.0, 5.1, 341.0, 0.0, 37.1, 8.9, 64.0, 0.0],
        [7.9, 5742.0, 15.6, 488.0, 2.5, 115.0, 0.0, 13.8, 8.5, 126.0, 0.0],
        [9.1, 4985.0, 12.2, 484.0, 2.7, 125.0, 0.0, 13.9, 6.4, 160.0, 0.0],
        [9.2, 4930.0, 12.4, 439.0, 1.1, 82.0, 0.0, 9.9, 3.0, 66.0, 0.0],
        [24.8, 1829.0, 8.0, 130.0, 0.4, 31.0, 18.9, 2.8, 3.0, 17.0, 0.0],
        [15.1, 3004.0, 12.5, 288.0, 0.5, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        [11.0, 8867.0, 6.1, 310.0, 10.5, 18.0, 16.8, 4.0, 16.0, 7.0, 177.0],
        [6.7, 6035.0, 8.4, 422.0, 15.1, 9.0, 26.0, 3.0, 23.5, 11.0, 60.0],
        [20.8, 1473.0, 10.8, 9.0, 0.2, 3.0, 44.2, 0.0, 0.2, 2.0, 0.0],
        [16.1, 2817.0, 20.6, 17.0, 0.6, 6.0, 55.8, 0.2, 0.0, 0.0, 0.0],
        [32.6, 1857.0, 2.9, 238.0, 1.0, 52.0, 18.6, 2.8, 6.5, 1.0, 0.0],
        [24.2, 1874.0, 7.4, 448.0, 16.4, 19.0, 28.1, 0.8, 10.3, 4.0, 0.0],
        [14.1, 1689.0, 3.5, 49.0, 1.7, 3.0, 16.9, 0.6, 2.5, 0.0, 17.0],
        [17.9, 2534.0, 15.7, 661.0, 1.0, 48.0, 0.0, 9.6, 8.1, 471.0, 0.0],
        [16.7, 1198.0, 8.6, 18.0, 0.2, 8.0, 2.7, 0.4, 0.5, 0.0, 0.0],
        [20.3, 2234.0, 20.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        [9.8, 4628.0, 41.7, 0.0, 0.0, 0.0, 0.2, 0.0, 0.5, 5.0, 0.0],
        [39.6, 1145.0, 2.9, 166.0, 0.1, 34.0, 0.2, 2.1, 2.9, 69.0, 0.0],
        [36.4, 1246.0, 2.2, 214.0, 0.1, 32.0, 0.4, 2.5, 2.4, 87.0, 0.0],
        [29.2, 1553.0, 3.4, 213.0, 0.1, 33.0, 0.0, 0.0, 2.0, 0.0, 0.0],
        [22.6, 2007.0, 3.6, 309.0, 0.2, 46.0, 0.4, 1.0, 4.0, 120.0, 0.0],
        [14.6, 3107.0, 8.5, 404.0, 0.2, 62.0, 0.0, 0.9, 0.0, 0.0, 0.0],
        [26.8, 1692.0, 2.2, 333.0, 0.2, 139.0, 169.2, 6.4, 50.8, 316.0, 525.0],
        [27.6, 1643.0, 3.1, 245.0, 0.1, 20.0, 0.0, 2.8, 3.0, 86.0, 0.0],
        [36.6, 1239.0, 3.3, 140.0, 0.1, 15.0, 0.0, 1.7, 2.7, 54.0, 0.0],
        [30.7, 1477.0, 3.5, 196.0, 0.2, 80.0, 0.0, 17.4, 2.7, 60.0, 0.0],
        [24.2, 1874.0, 4.4, 249.0, 0.3, 37.0, 0.0, 18.2, 3.6, 79.0, 0.0],
        [25.6, 1772.0, 10.4, 152.0, 0.2, 23.0, 0.0, 1.8, 1.8, 71.0, 0.0],
        [27.4, 1655.0, 6.7, 212.0, 0.2, 31.0, 0.0, 9.9, 3.3, 50.0, 0.0],
        [16.0, 2835.0, 18.8, 164.0, 0.1, 26.0, 0.0, 1.4, 1.8, 0.0, 0.0],
        [30.3, 1497.0, 1.8, 184.0, 0.1, 30.0, 0.1, 0.9, 1.8, 68.0, 46.0],
        [42.3, 1072.0, 1.7, 156.0, 0.1, 24.0, 0.0, 1.4, 2.4, 57.0, 0.0],
        [13.0, 3489.0, 5.8, 705.0, 6.8, 45.0, 3.5, 1.0, 4.9, 209.0, 0.0],
        [4.4, 9072.0, 5.8, 27.0, 0.5, 36.0, 7.3, 3.6, 2.7, 5.0, 544.0],
        [6.1, 4982.0, 4.9, 60.0, 0.4, 30.0, 17.4, 2.5, 3.5, 28.0, 498.0],
        [26.0, 2380.0, 1.0, 21.0, 0.5, 14.0, 0.0, 0.5, 0.0, 4.0, 952.0],
        [30.9, 4439.0, 2.2, 40.0, 1.1, 18.0, 11.1, 3.6, 1.3, 10.0, 1993.0],
        [7.1, 5750.0, 2.4, 138.0, 3.7, 80.0, 69.0, 4.3, 5.8, 37.0, 862.0],
        [3.7, 8949.0, 2.6, 125.0, 4.0, 36.0, 7.2, 9.0, 4.5, 26.0, 5369.0],
        [4.7, 6080.0, 2.7, 73.0, 2.8, 43.0, 188.5, 6.1, 4.3, 89.0, 608.0],
        [7.3, 3915.0, 0.9, 51.0, 3.0, 23.0, 0.9, 1.4, 1.4, 9.0, 313.0],
        [8.2, 2247.0, 0.4, 27.0, 1.1, 22.0, 112.4, 1.8, 3.4, 11.0, 449.0],
        [3.6, 11844.0, 5.8, 166.0, 3.8, 59.0, 16.6, 4.7, 5.9, 21.0, 1184.0],
        [
            34.0, 16810.0, 14.3, 336.0, 1.8, 118.0, 6.7, 29.4, 7.1, 198.0,
            2522.0
        ],
        [8.1, 4592.0, 1.1, 106.0, 0.0, 138.0, 918.4, 5.7, 13.8, 33.0, 2755.0],
        [5.1, 7649.0, 9.6, 138.0, 2.7, 54.0, 290.7, 8.4, 5.4, 83.0, 1912.0],
        [16.8, 4894.0, 3.7, 20.0, 0.4, 10.0, 21.5, 0.5, 1.0, 31.0, 196.0],
        [20.4, 4030.0, 3.0, 8.0, 0.3, 8.0, 0.8, 0.8, 0.8, 5.0, 81.0],
        [21.3, 3993.0, 2.4, 16.0, 0.4, 8.0, 2.0, 2.8, 0.8, 7.0, 399.0],
        [27.7, 1945.0, 0.4, 33.0, 0.3, 12.0, 16.3, 1.4, 2.1, 17.0, 272.0],
        [10.0, 5386.0, 1.0, 54.0, 2.0, 65.0, 53.9, 1.6, 4.3, 32.0, 431.0],
        [7.1, 6389.0, 7.5, 364.0, 4.0, 134.0, 3.5, 8.3, 7.7, 56.0, 0.0],
        [10.4, 5452.0, 5.2, 136.0, 0.2, 16.0, 12.0, 1.6, 2.7, 42.0, 218.0],
        [13.8, 4109.0, 2.3, 136.0, 0.6, 45.0, 34.9, 4.9, 2.5, 37.0, 370.0],
        [8.6, 6263.0, 1.3, 63.0, 0.7, 38.0, 53.2, 3.4, 2.5, 36.0, 1253.0],
        [7.6, 3917.0, 1.6, 71.0, 0.6, 43.0, 57.9, 3.5, 2.4, 67.0, 862.0],
        [15.7, 2889.0, 8.5, 87.0, 1.7, 173.0, 86.8, 1.2, 4.3, 55.0, 57.0],
        [9.0, 4284.0, 12.8, 99.0, 2.5, 154.0, 85.7, 3.9, 4.3, 65.0, 257.0],
        [9.4, 4524.0, 13.5, 104.0, 2.5, 136.0, 4.5, 6.3, 1.4, 24.0, 136.0],
        [7.9, 5742.0, 20.0, 1367.0, 4.2, 345.0, 2.9, 28.7, 18.4, 162.0, 0.0],
        [8.9, 5097.0, 17.4, 1055.0, 3.7, 459.0, 5.1, 26.9, 38.2, 93.0, 0.0],
        [5.9, 7688.0, 26.9, 1691.0, 11.4, 792.0, 0.0, 38.4, 24.6, 217.0, 0.0],
        [22.4, 2025.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.1, 50.0, 0.0],
        [17.4, 652.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.3, 42.0, 0.0],
        [8.6, 2637.0, 8.7, 237.0, 3.0, 72.0, 0.0, 2.0, 11.9, 40.0, 0.0],
        [16.2, 1400.0, 8.0, 77.0, 1.3, 39.0, 0.0, 0.9, 3.4, 14.0, 0.0],
        [51.7, 8773.0, 34.9, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        [13.7, 4996.0, 14.7, 0.0, 0.5, 74.0, 0.0, 0.0, 0.0, 5.0, 0.0],
        [13.6, 3752.0, 9.0, 0.0, 10.3, 244.0, 0.0, 1.9, 7.5, 146.0, 0.0],
        [20.5, 2213.0, 6.4, 11.0, 0.4, 7.0, 0.2, 0.2, 0.4, 3.0, 0.0]
    ]

    # recommended daily allowance for a moderately active man
    allowance = [3.0, 70.0, 0.8, 12.0, 5.0, 1.8, 2.7, 18.0, 75.0]

    #
    # variables
    #
    x = [solver.NumVar(0, 1000, 'x[%i]' % i) for i in C]
    x_cost = [solver.NumVar(0, 1000, 'x_cost[%i]' % i) for i in C]
    quant = [solver.NumVar(0, 1000, 'quant[%i]' % i) for i in C]

    # total food bill
    total_cost = solver.NumVar(0, 1000, 'total_cost')

    # cost per day, to minimize
    cost = solver.Sum(x)

    #
    # constraints
    #
    solver.Add(total_cost == days * cost)  # cost per year

    for c in C:
        solver.Add(x_cost[c] == days * x[c])
        solver.Add(quant[c] == 100.0 * days * x[c] / data[c][0])

    # nutrient balance
    for n in range(2, num_nutrients + 2):
        solver.Add(
            solver.Sum([data[c][n] * x[c] for c in C]) >= allowance[n - 2])

    objective = solver.Minimize(cost)

    #
    # solution and search
    #
    solver.Solve()

    print

    print 'Cost = %0.2f' % solver.ObjectiveValue()
    # print 'Cost:', cost.SolutionValue()
    print 'Total cost: %0.2f' % total_cost.SolutionValue()
    print
    for i in C:
        if x[i].SolutionValue() > 0:
            print "%-21s %-11s  %0.2f  %0.2f" % (
                commodities[i][0], commodities[i][1],
                x_cost[i].SolutionValue(), quant[i].SolutionValue())

    print

    print 'walltime  :', solver.WallTime(), 'ms'
    if sol == 'CBC':
        print 'iterations:', solver.Iterations()
Пример #24
0
def main(sol = 'GLPK'):
  
  # Create the solver.

  print 'Solver: ', sol

  # using GLPK
  if sol == 'GLPK':
    solver = pywraplp.Solver('CoinsGridGLPK',
                             pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
  else:
  # Using CLP
      solver = pywraplp.Solver('CoinsGridCLP',
                               pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)


  #
  # data
  #
  n = 9
  range_n = range(1, n + 1)
  
  X = -1
  # Example from Wikipedia
  givens = [[5, 3, X, X, 7, X, X, X, X],
            [6, X, X, 1, 9, 5, X, X, X],
            [X, 9, 8, X, X, X, X, 6, X],
            [8, X, X, X, 6, X, X, X, 3],
            [4, X, X, 8, X, 3, X, X, 1],
            [7, X, X, X, 2, X, X, X, 6],
            [X, 6, X, X, X, X, 2, 8, X],
            [X, X, X, 4, 1, 9, X, X, 5],
            [X, X, X, X, 8, X, X, 7, 9]]

  #
  # variables
  #

  # x[i,j,k] = 1 means cell [i,j] is assigned number k
  x = {}
  for i in range_n:
    for j in range_n:
      for k in range_n:      
        x[i,j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k))

  #
  # constraints
  #
  
  # assign pre-defined numbers using the "givens"
  for i in range_n:
    for j in range_n:
      for k in range_n:
        if givens[i-1][j-1] > X:
          if givens[i-1][j-1] == k:
            solver.Add(x[i,j,k] == 1)
          else:
            solver.Add(x[i,j,k] == 0)

  # each cell must be assigned exactly one number 
  for i in range_n:
    for j in range_n:
      solver.Add(solver.Sum([x[i,j,k] for k in range_n]) == 1)

  # cells in the same row must be assigned distinct numbers
  for i in range_n:
    for k in range_n:
      solver.Add(solver.Sum([x[i,j,k] for j in range_n]) == 1)

  # cells in the same column must be assigned distinct numbers
  for j in range_n:
    for k in range_n:
      solver.Add(solver.Sum([x[i,j,k] for i in range_n]) == 1)

  # cells in the same region must be assigned distinct numbers
  R = [1, 4, 7]
  for I in R:
    for J in R:
      for k in range_n:
        solver.Add(solver.Sum([x[i,j,k]
                               for i in range(I,I+3)
                               for j in range(J,J+3)])  == 1)


  #
  # solution and search
  #
  solver.Solve()

  print

  print 'Matrix:'
  for i in range_n:
    for j in range_n:
      for k in range_n:
        if x[i,j,k].solution_value() == 1:
          print k,
    print
  print



  print
  print 'walltime  :', solver.wall_time(), 'ms'
  if sol == 'CBC':
    print 'iterations:', solver.iterations()
Пример #25
0
def main(sol='GLPK'):

    # Create the solver.

    print 'Solver: ', sol

    if sol == 'GLPK':
        # using GLPK
        solver = pywraplp.Solver(
            'CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
    else:
        # Using CBC
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    #
    # data
    #

    # max number of colors
    # [we know that 4 suffices for normal maps]
    nc = 5

    # number of nodes
    n = 11
    # set of nodes
    V = range(n)

    num_edges = 20

    #
    # Neighbours
    #
    # This data correspond to the instance myciel3.col from:
    # http://mat.gsia.cmu.edu/COLOR/instances.html
    #
    # Note: 1-based (adjusted below)
    E = [[1, 2], [1, 4], [1, 7], [1, 9], [2, 3], [2, 6], [2, 8], [3, 5],
         [3, 7], [3, 10], [4, 5], [4, 6], [4, 10], [5, 8], [5, 9], [6, 11],
         [7, 11], [8, 11], [9, 11], [10, 11]]

    #
    # declare variables
    #

    # x[i,c] = 1 means that node i is assigned color c
    x = {}
    for v in V:
        for j in range(nc):
            x[v, j] = solver.IntVar(0, 1, 'v[%i,%i]' % (v, j))

    # u[c] = 1 means that color c is used, i.e. assigned to some node
    u = [solver.IntVar(0, 1, 'u[%i]' % i) for i in range(nc)]

    # number of colors used, to minimize
    obj = solver.Sum(u)

    #
    # constraints
    #

    # each node must be assigned exactly one color
    for i in V:
        solver.Add(solver.Sum([x[i, c] for c in range(nc)]) == 1)

    # adjacent nodes cannot be assigned the same color
    # (and adjust to 0-based)
    for i in range(num_edges):
        for c in range(nc):
            solver.Add(x[E[i][0] - 1, c] + x[E[i][1] - 1, c] <= u[c])

    # objective
    objective = solver.Minimize(obj)

    #
    # solution
    #
    solver.Solve()

    print
    print "number of colors:", int(solver.ObjectiveValue())
    print "colors used:", [int(u[i].SolutionValue()) for i in range(nc)]
    print

    for v in V:
        print 'v%i' % v, ' color ',
        for c in range(nc):
            if int(x[v, c].SolutionValue()) == 1:
                print c

    print
    print "WallTime:", solver.WallTime()
    if sol == 'CBC':
        print 'iterations:', solver.Iterations()
Пример #26
0
def main(sol='GLPK'):

    # Create the solver.

    print 'Solver: ', sol

    # using GLPK
    if sol == 'GLPK':
        solver = pywraplp.Solver(
            'CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
    else:
        # Using CLP
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    #
    # data
    #

    # number of agents
    m = 8

    # number of tasks
    n = 8

    # set of agents
    I = range(m)

    # set of tasks
    J = range(n)

    # cost of allocating task j to agent i
    # """
    # These data correspond to an example from [Christofides].
    #
    # Optimal solution is 76
    # """
    c = [[13, 21, 20, 12, 8, 26, 22, 11], [12, 36, 25, 41, 40, 11, 4, 8],
         [35, 32, 13, 36, 26, 21, 13, 37], [34, 54, 7, 8, 12, 22, 11, 40],
         [21, 6, 45, 18, 24, 34, 12, 48], [42, 19, 39, 15, 14, 16, 28, 46],
         [16, 34, 38, 3, 34, 40, 22, 24], [26, 20, 5, 17, 45, 31, 37, 43]]

    #
    # variables
    #

    # For the output: the assignment as task number.
    assigned = [solver.IntVar(0, 10000, 'assigned[%i]' % j) for j in J]

    costs = [solver.IntVar(0, 10000, 'costs[%i]' % i) for i in I]

    x = {}
    for i in range(n):
        for j in range(n):
            x[i, j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))

    # total cost, to be minimized
    z = solver.Sum([c[i][j] * x[i, j] for i in I for j in J])

    #
    # constraints
    #
    # each agent can perform at most one task
    for i in I:
        solver.Add(solver.Sum([x[i, j] for j in J]) <= 1)

    # each task must be assigned exactly to one agent
    for j in J:
        solver.Add(solver.Sum([x[i, j] for i in I]) == 1)

    # to which task and what cost is person i assigned (for output in MiniZinc)
    for i in I:
        solver.Add(assigned[i] == solver.Sum([j * x[i, j] for j in J]))
        solver.Add(costs[i] == solver.Sum([c[i][j] * x[i, j] for j in J]))

    # objective
    objective = solver.Minimize(z)

    #
    # solution and search
    #
    solver.Solve()

    print
    print 'z: ', int(solver.ObjectiveValue())

    print 'Assigned'
    for j in J:
        print int(assigned[j].SolutionValue()),
    print

    print 'Matrix:'
    for i in I:
        for j in J:
            print int(x[i, j].SolutionValue()),
        print
    print

    print
    print 'walltime  :', solver.WallTime(), 'ms'
    if sol == 'CBC':
        print 'iterations:', solver.Iterations()
Пример #27
0
def main(sol = 'GLPK'):

  # Create the solver.

  print 'Solver: ', sol

  # using GLPK
  if sol == 'GLPK':
    solver = pywraplp.Solver('CoinsGridGLPK',
                             pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
  else:
  # Using CLP
      solver = pywraplp.Solver('CoinsGridCLP',
                               pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)


  #
  # data
  #
  n = 15
  start = 0 # start node
  end = 14  # end node
  M = 999   # a large number

  nodes = ['8,0,0', # start
           '5,0,3',
           '5,3,0',
           '2,3,3',
           '2,5,1',
           '7,0,1',
           '7,1,0',
           '4,1,3',
           '3,5,0',
           '3,2,3',
           '6,2,0',
           '6,0,2',
           '1,5,2',
           '1,4,3',
           '4,4,0'  # goal!
          ]

  # distance
  d = [[M, 1, M, M, M, M, M, M, 1, M, M, M, M, M, M],
       [M, M, 1, M, M, M, M, M, M, M, M, M, M, M, M],
       [M, M, M, 1, M, M, M, M, 1, M, M, M, M, M, M],
       [M, M, M, M, 1, M, M, M, M, M, M, M, M, M, M],
       [M, M, M, M, M, 1, M, M, 1, M, M, M, M, M, M],
       [M, M, M, M, M, M, 1, M, M, M, M, M, M, M, M],
       [M, M, M, M, M, M, M, 1, 1, M, M, M, M, M, M],
       [M, M, M, M, M, M, M, M, M, M, M, M, M, M, 1],
       [M, M, M, M, M, M, M, M, M, 1, M, M, M, M, M],
       [M, 1, M, M, M, M, M, M, M, M, 1, M, M, M, M],
       [M, M, M, M, M, M, M, M, M, M, M, 1, M, M, M],
       [M, 1, M, M, M, M, M, M, M, M, M, M, 1, M, M],
       [M, M, M, M, M, M, M, M, M, M, M, M, M, 1, M],
       [M, 1, M, M, M, M, M, M, M, M, M, M, M, M, 1],
       [M, M, M, M, M, M, M, M, M, M, M, M, M, M, M]]


  #
  # variables
  #

  # requirements (right hand statement)
  rhs = [solver.IntVar(-1, 1, 'rhs[%i]' % i) for i in range(n)]

  x = {}
  for i in range(n):
    for j in range(n):
        x[i,j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))

  out_flow = [solver.IntVar(0, 1, 'out_flow[%i]' % i) for i in range(n)]
  in_flow = [solver.IntVar(0, 1, 'in_flow[%i]' % i) for i in range(n)]

  # length of path, to be minimized
  z = solver.Sum([d[i][j]*x[i,j]
                               for i in range(n)
                               for j in range(n) if d[i][j] < M])

  #
  # constraints
  #


  for i in range(n):
    if i == start:
      solver.Add(rhs[i] == 1)
    elif i == end:
      solver.Add(rhs[i] == -1)
    else:
      solver.Add(rhs[i] == 0)


  # outflow constraint
  for i in range(n):
    solver.Add(out_flow[i] == solver.Sum([x[i,j]
                                          for j in range(n)
                                          if d[i][j] < M]))

  # inflow constraint
  for j in range(n):
    solver.Add(in_flow[j] == solver.Sum([x[i,j]
                                         for i in range(n)
                                         if d[i][j] < M]))

  # inflow = outflow
  for i in range(n):
     solver.Add(out_flow[i]-in_flow[i] == rhs[i])


  # objective
  objective = solver.Minimize(z)


  #
  # solution and search
  #
  solver.Solve()

  print
  print 'z: ', int(solver.ObjectiveValue())

  t = start
  while t != end:
    print nodes[t], '->',
    for j in range(n):
      if x[t,j].SolutionValue() == 1:
        print nodes[j]
        t = j
        break

  print
  print 'walltime  :', solver.WallTime(), 'ms'
  if sol == 'CBC':
    print 'iterations:', solver.Iterations()
Пример #28
0
def main(sol='GLPK'):

    # Create the solver.

    print 'Solver: ', sol

    # using GLPK
    if sol == 'GLPK':
        solver = pywraplp.Solver(
            'CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
    else:
        # Using CLP
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    #
    # data
    #
    NbMetals = 3
    NbRaw = 2
    NbScrap = 2
    NbIngo = 1
    Metals = range(NbMetals)
    Raws = range(NbRaw)
    Scraps = range(NbScrap)
    Ingos = range(NbIngo)

    CostMetal = [22, 10, 13]
    CostRaw = [6, 5]
    CostScrap = [7, 8]
    CostIngo = [9]
    Low = [0.05, 0.30, 0.60]
    Up = [0.10, 0.40, 0.80]
    PercRaw = [[0.20, 0.01], [0.05, 0], [0.05, 0.30]]
    PercScrap = [[0, 0.01], [0.60, 0], [0.40, 0.70]]
    PercIngo = [[0.10], [0.45], [0.45]]
    Alloy = 71

    #
    # variables
    #
    p = [solver.NumVar(0, solver.Infinity(), 'p[%i]' % i) for i in Metals]
    r = [solver.NumVar(0, solver.Infinity(), 'r[%i]' % i) for i in Raws]
    s = [solver.NumVar(0, solver.Infinity(), 's[%i]' % i) for i in Scraps]
    ii = [solver.IntVar(0, solver.Infinity(), 'ii[%i]' % i) for i in Ingos]
    metal = [
        solver.NumVar(Low[j] * Alloy, Up[j] * Alloy, 'metal[%i]' % j)
        for j in Metals
    ]

    z = solver.NumVar(0, solver.Infinity(), 'z')

    #
    # constraints
    #

    solver.Add(z == solver.Sum([CostMetal[i] * p[i] for i in Metals]) +
               solver.Sum([CostRaw[i] * r[i] for i in Raws]) +
               solver.Sum([CostScrap[i] * s[i] for i in Scraps]) +
               solver.Sum([CostIngo[i] * ii[i] for i in Ingos]))

    for j in Metals:
        solver.Add(metal[j] == p[j] +
                   solver.Sum([PercRaw[j][k] * r[k] for k in Raws]) +
                   solver.Sum([PercScrap[j][k] * s[k] for k in Scraps]) +
                   solver.Sum([PercIngo[j][k] * ii[k] for k in Ingos]))

    solver.Add(solver.Sum(metal) == Alloy)

    objective = solver.Minimize(z)

    #
    # solution and search
    #
    solver.Solve()

    print

    print 'z = ', solver.ObjectiveValue()
    print 'Metals'
    for i in Metals:
        print p[i].SolutionValue(),
    print

    print 'Raws'
    for i in Raws:
        print r[i].SolutionValue(),
    print

    print 'Scraps'
    for i in Scraps:
        print s[i].SolutionValue(),
    print

    print 'Ingos'
    for i in Ingos:
        print ii[i].SolutionValue(),
    print

    print 'Metals'
    for i in Metals:
        print metal[i].SolutionValue(),
    print

    print

    print 'walltime  :', solver.WallTime(), 'ms'
    if sol == 'CBC':
        print 'iterations:', solver.Iterations()
Пример #29
0
def main(n=3, sol='GLPK', use_output_matrix=0):

    # Create the solver.

    print 'Solver: ', sol

    # using GLPK
    if sol == 'GLPK':
        solver = pywraplp.Solver(
            'CoinsGridGLPK', pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
    else:
        # Using CLP
        solver = pywraplp.Solver('CoinsGridCLP',
                                 pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    #
    # data
    #
    print 'n = ', n

    # range_n = range(1, n+1)
    range_n = range(0, n)

    N = n * n
    range_N = range(1, N + 1)

    #
    # variables
    #

    # x[i,j,k] = 1 means that cell (i,j) contains integer k
    x = {}
    for i in range_n:
        for j in range_n:
            for k in range_N:
                x[i, j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k))

    ## For output. Much slower....
    if use_output_matrix == 1:
        print 'Using an output matrix'
        square = {}
        for i in range_n:
            for j in range_n:
                square[i, j] = solver.IntVar(1, n * n,
                                             'square[%i,%i]' % (i, j))

    # the magic sum
    s = solver.IntVar(1, n * n * n, 's')

    #
    # constraints
    #

    # each cell must be assigned exactly one integer
    for i in range_n:
        for j in range_n:
            solver.Add(solver.Sum([x[i, j, k] for k in range_N]) == 1)

    # each integer must be assigned exactly to one cell
    for k in range_N:
        solver.Add(
            solver.Sum([x[i, j, k] for i in range_n for j in range_n]) == 1)

    # # the sum in each row must be the magic sum
    for i in range_n:
        solver.Add(
            solver.Sum([k * x[i, j, k] for j in range_n
                        for k in range_N]) == s)

    # # the sum in each column must be the magic sum
    for j in range_n:
        solver.Add(
            solver.Sum([k * x[i, j, k] for i in range_n
                        for k in range_N]) == s)

    # # the sum in the diagonal must be the magic sum
    solver.Add(
        solver.Sum([k * x[i, i, k] for i in range_n for k in range_N]) == s)

    # # the sum in the co-diagonal must be the magic sum
    if range_n[0] == 1:
        # for range_n = 1..n
        solver.Add(
            solver.Sum(
                [k * x[i, n - i + 1, k] for i in range_n
                 for k in range_N]) == s)
    else:
        # for range_n = 0..n-1
        solver.Add(
            solver.Sum(
                [k * x[i, n - i - 1, k] for i in range_n
                 for k in range_N]) == s)

    # for output
    if use_output_matrix == 1:
        for i in range_n:
            for j in range_n:
                solver.Add(
                    square[i,
                           j] == solver.Sum([k * x[i, j, k] for k in range_N]))

    #
    # solution and search
    #
    solver.Solve()

    print

    print 's: ', int(s.SolutionValue())
    if use_output_matrix == 1:
        for i in range_n:
            for j in range_n:
                print int(square[i, j].SolutionValue()),
            print
        print
    else:
        for i in range_n:
            for j in range_n:
                print sum([
                    int(k * x[i, j, k].SolutionValue()) for k in range_N
                ]), " ",
            print

    print "\nx:"
    for i in range_n:
        for j in range_n:
            for k in range_N:
                print int(x[i, j, k].SolutionValue()),
            print

    print
    print 'walltime  :', solver.WallTime(), 'ms'
    if sol == 'CBC':
        print 'iterations:', solver.Iterations()