Examplecopy it from the repository's examples/
cpbenchy run instances/ -s ortools -t 60 --loader examples/loaders/knapsack_json.py:KnapsackJSON- Distributed as
- a file in examples/, to copy
- Last updated
- 6 Oct 2026 · 1 commit
- Authors
- ThomSerg
- Shows
- a Loader for a file format of your own
- Formats
- json
- Tags
- loader
What it does
Benchmarks problems stored in your own file format. This loader reads knapsack instances written as
JSON and builds the CPMpy model, inside the measured run, so building it is measured as parse_s, as
loading any other format is.
{"capacity": 50, "items": [{"weight": 10, "value": 60}, {"weight": 20, "value": 100}]}Use it
import cpbenchy
cpbenchy.run("examples/data/*.json", solvers=["ortools", "exact"], time_limit=60,
loader="examples/loaders/knapsack_json.py:KnapsackJSON")cpbenchy run examples/data/*.json -s ortools -s exact -t 60 --loader examples/loaders/knapsack_json.py:KnapsackJSONResults record the loader, so the same instance loaded another way is another run.
Implementation
The file examples/loaders/knapsack_json.py, 24 lines, as of this version of the docs.
"""Load your own instance files: knapsack problems as JSON.
cpbenchy run examples/data/*.json -s ortools -s exact -t 60 --loader examples/loaders/knapsack_json.py:KnapsackJSON
A file holds {"capacity": ..., "items": [{"weight": ..., "value": ...}, ...]}. The loader builds the
CPMpy model in the worker, so building it is measured as `parse_s`, like loading any other format.
"""
import json
import cpbenchy
class KnapsackJSON(cpbenchy.Loader):
def load(self, instance):
import cpmpy as cp
data = json.loads(self.read(instance.path)) # read() also handles .xz, .gz, ... files
weights = [item["weight"] for item in data["items"]]
values = [item["value"] for item in data["items"]]
take = cp.boolvar(shape=len(weights), name="take")
model = cp.Model(cp.sum(take * weights) <= data["capacity"])
model.maximize(cp.sum(take * values))
return model