Skip to content
cpbenchy 0.1.0.dev0 is in alpha: until version 1.0, commands, options, the Python API and the result format may still change. Pin the version you use.

KnapsackJSON

Benchmarks problems stored in your own file format, here knapsacks written as JSON.

Updated View as Markdown
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

Results 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.

examples/loaders/knapsack_json.pypython
"""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
Navigation

Type to search…

↑↓ navigate↵ selectEsc close