The knapsack problem is a well-known optimization problem. It is encountered, for example, in packing shipping containers. A shipping container has a weight capacity which it can hold. Given a collection of items to be shipped, where each item has a value and a weight, the problem is to select the optimal items to pack in the shipping container. This optimization problem can be defined as an objective with a constraint:
This example solves such a knapsack problem by reformulating it as a constrained quadratic model (CQM) and submitting it to a Leap hybrid CQM solver.
To run the default demo, enter the command:
python knapsack.py
To view available options, enter the command:
python knapsack.py --help
Command-line arguments let you select one of several data sets (under the /data
folder) and set the freight capacity. The data files are formulated as rows of
items, each defined as a pair of weight and value.
The code in knapsack.py
includes three main functions:
build_knapsack_cqm()
creates a CQM by setting an objective and constraint as
follows:
parse_inputs()
is a utility function that reads data from the example files.
parse_solution()
parses and displays the results returned from the solver.
Released under the Apache License 2.0. See LICENSE file.