Skip to content

Commit

Permalink
add knapsack model
Browse files Browse the repository at this point in the history
  • Loading branch information
mabdullahsoyturk committed Jun 25, 2024
1 parent 13624e0 commit 5994c80
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ List of models under `models` directory is listed below. Most models have a GAMS
| [InternationalMeanVar](models/InternationalMeanVar) | [InternationalMeanVar](https://www.gams.com/latest/finlib_ml/libhtml/finlib_InternationalMeanVar.html) | NLP | Demo |
| [invmat](models/invmat) | | LP | Demo |
| [iobalance](models/iobalance) | [iobalance](https://www.gams.com/latest/gamslib_ml/libhtml/gamslib_iobalance.html) | LP, NLP, QCP | Demo |
| [knapsack](models/knapsack) | | MIP | Demo |
| [korcns](models/korcns) | [korcns](https://www.gams.com/latest/gamslib_ml/libhtml/gamslib_korcns.html) | CNS | Demo |
| [linear](models/linear) | [linear](https://www.gams.com/latest/gamslib_ml/libhtml/gamslib_linear.html) | DNLP, LP, NLP | Demo |
| [lop](models/lop) | [lop](https://www.gams.com/latest/gamslib_ml/libhtml/gamslib_lop.html) | LP, MIP | Demo |
Expand Down
11 changes: 11 additions & 0 deletions models/knapsack/f1_l-d_kp_10_269
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
10 269
55 95
10 4
47 60
5 32
4 23
50 72
8 80
61 62
85 65
87 46
82 changes: 82 additions & 0 deletions models/knapsack/knapsack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import math
import sys
from pathlib import Path

from gamspy import (
Container,
Equation,
Model,
Parameter,
Problem,
Sense,
Set,
Sum,
Variable,
VariableType,
)

# Declaration
m = Container()
i = Set(m, "i", description="items")
p = Parameter(m, "p", description="profits", domain=i)
w = Parameter(m, "p", description="weights", domain=i)
c = Parameter(m, "c", description="capacity")
x = Variable(m, "x", domain=i, description="chosen", type=VariableType.BINARY)

cap_restr = Equation(m, name="capacity_restriction")
cap_restr[...] = Sum(i, w[i] * x[i]) <= c

utility = Sum(i, p[i] * x[i])

knapsack = Model(
m,
name="knapsack",
equations=m.getEquations(),
problem=Problem.MIP,
sense=Sense.MAX,
objective=utility,
)


# Instance data
def load_instance_from_file(filename):
def ints(elems):
return [int(elem) for elem in elems]

global items, capacity, profits, weights
items, capacity, profits, weights = [], [], [], []
num_items = None
with open(filename) as fp:
for line in fp.readlines():
if not line.strip():
continue
parts = line.split()
assert len(parts) == 2
if not num_items:
num_items, capacity = ints(parts)
continue
profits.append(parts[0])
weights.append(parts[1])
assert num_items
items = [f"i{i + 1}" for i in range(num_items)]


# Example instance taken from
# http://artemisa.unicauca.edu.co/~johnyortega/instances_01_KP/
# and also available at https://github.com/JordiHOFC/knapsackproblemboolean
load_instance_from_file(
str(Path(__file__).parent.absolute()) + "/f1_l-d_kp_10_269"
)
i.setRecords(items)
p.setRecords(zip(items, profits))
w.setRecords(zip(items, weights))
c.setRecords(capacity)

# Run solve and display results
knapsack.solve(output=sys.stdout)
print(f"Objective function value = {knapsack.objective_value}")
assert math.isclose(knapsack.objective_value, 269.0, rel_tol=0.001)
levels = list(x.records["level"])
print(
f'Chosen items = {", ".join([j for ix, j in enumerate(items) if levels[ix] == 1.0])}'
)

0 comments on commit 5994c80

Please sign in to comment.