minizinc#
- pykp.solvers.minizinc(items: list[Item], capacity: float, solver: str = 'coinbc') Solution#
Solves the knapsack problem using the MiniZinc.
- Parameters:
- itemslist[Item]
Array of items to consider for the knapsack.
- capacityfloat
Maximum weight capacity of the knapsack.
- solver: str, optional
MiniZinc solver to use. Default is “coinbc”.
- Returns:
- SolutionSolution
The optimal arrangement of items in the knapsack.
Examples
Solve a knapsack problem instance using MiniZinc and the COIN-OR Branch-and-Cut solver:
>>> from pykp.knapsack import Item >>> from pykp import solvers >>> items = np.array( ... [ ... Item(value=10, weight=5), ... Item(value=15, weight=10), ... Item(value=5, weight=5), ... ] ... ) >>> capacity = 15 >>> solvers.minizinc(items, capacity, solver="coinbc") [(v: 25, w: 15, s: 6)]
Alternatively, construct an instance of the
Knapsackclass and call thesolvemethod with “minizinc” as themethodargument>>> from pykp.knapsack import Item >>> from pykp.knapsack import Knapsack >>> >>> items = [ ... Item(value=10, weight=5), ... Item(value=15, weight=10), ... Item(value=5, weight=5), ... ] >>> capacity = 15 >>> instance = Knapsack(items=items, capacity=capacity) >>> instance.solve(method="minizinc") >>> instance.optimal_nodes [(v: 25, w: 15, s: 6)]
Note
You should have MiniZinc 2.5.0 (or higher) installed on your system to use this solver. Refer to the MiniZinc documentation for installation instructions.
Note
The MiniZinc Gecode solver is not robust to multiple solutions, and will report only the first optimal solution found. If knowing all optimal solutions is important, consider using the branch-and-bound solver.