1

Python Cplex を使用したスカラーではなく、各項目が 1 つの値が選択される値のベクトルである 0-1 ナップザック問題のわずかな修正を解決しようとしています。これは混合整数問題の一種です。この問題に対するIBM OPLソリューションを作成しましたが、Python Cplexを使用して解決する方法がわかりません。IBM OPL を使用した私のソリューションは次のとおりです。

int Capacity = 100; // Capacity of the knapsack
int k = 2;   // Number of items
int n = 5;  // Number of values
range values = 1..n;
range items = 1..k;

// parameters
int profit[items][values] = [[ 5, 10, 20, 20, 20],  // only one item should be selected from this list
                             [ 5, 20, 25, 30, 40]]; // only one item should be selected from this list
int weight[values]        =  [ 10, 20, 50, 70, 80]; // Corresponding weights


// decision variable x[i][j]=1 if the jth item is selected
dvar boolean x[items][values];

// objective function
maximize sum(i in items, j in values) x[i][j] * p[i][j];

// constraints
subject to{

sum(i in items, j in values) x[i][j] * w[j] <= Capacity;
forall(i in items) sum(j in values) x[i][j] <= 1;

}

この問題は として実行できますoplrun -v knapsack.mod。この問題の解決策は、

x = [[0 1 0 0 0]
     [0 0 0 0 1]];
profit = 10 + 40
       = 50

問題の数学的定式化は次のとおりです。

ナップザックの数式

Python CPLEX を使用して、上記と同じソリューションを取得しようとしています。次のコードは、問題を解決しようとする試みですが、正しくありません。解決方法がわかりません:

import cplex


capacity = 100  # Capacity of the cache
k = 2  # Number of items
n = 5  # Number values for each item
profit = [[5, 10, 20, 20, 20],
          [5, 10, 25, 30, 40]]
weight = [10, 20, 50, 70, 80]
xvar = []  # Will contain the solution


def setupproblem(c):
    c.objective.set_sense(c.objective.sense.maximize)

    # xvars[i][j] = 1 if ith item and jth value is selected
    allxvars = []
    for i in range(k):
        xvar.append([])
        for j in range(n):
            varname = "assign_" + str(i) + "_" + str(j)
            allxvars.append(varname)
            xvar[i].append(varname)

    # not sure how to formulate objective
    c.variables.add(names=allxvars, lb=[0] * len(allxvars),
                    ub=[1] * len(allxvars))

    # Exactly one value must be selected from each item
    # and the corresponding weights must not exceed capacity
    # Not sure about this too.
    for j in range(k):
        thevars = []
        for i in range(n):
            thevars.append(xvar[i][j])
        c.linear_constraints.add(
                    lin_expr=[cplex.SparsePair(thevars, [1] * len(thevars))],
                    senses=["L"],
                    rhs=capacity)


def knapsack():
    c = cplex.Cplex()

    setupproblem(c)
    c.solve()
    sol = c.solution

if __name__ == "__main__":
    knapsack()
4

1 に答える 1