pykp.sampling.

Sampler#

class pykp.sampling.Sampler(num_items: int, normalised_capacity: float | tuple[float, float], weight_dist: str = 'uniform', value_dist: str = 'uniform', weight_dist_kwargs: dict | None = None, value_dist_kwargs: dict | None = None)#

Generate random knapsack instances.

Sample knapsack instances by specifying the number of items, normalised capacity, and optionally custom distributions for weights and values.

Parameters:
num_itemsint

Number of items to include in each sampled knapsack instance.

normalised_capacityfloat | tuple[float, float]

Normalised capacity of the knapsack, defined as the sum of item weights divided by the capacity constraint. Must be in the interval (0, 1). If a tuple is provided, the capacity will be sampled uniformly from the specified interval.

Methods

sample([seed])

Generate a random knapsack instance.

Other Parameters:
weight_diststr, optional

Name of the distribution to sample item weights from. Defaults to uniform distribution over the half-open interval [0.001, 1).

weight_dist_kwargsdict, optional

Additional keyword arguments to pass to the weight distribution function. Defaults to None.

value_diststr, optional

Name of the distribution to sample item values from. Defaults to uniform distribution over the half-open interval [0.001, 1).

value_dist_kwargsdict, optional

Additional keyword arguments to pass to the value distribution function. Defaults to None.

.. note::

Find a list of available distributions in the numpy.random.Generator documentation: https://numpy.org/doc/stable/reference/random/generator.html#distributions.

Raises:
ValueError

If weight_dist is specified without providing weight_dist_kwargs. If value_dist is specified without providing value_dist_kwargs.

Examples

Sample a random knapsack instance by sampling from default distributions:
>>> from pykp.sampler import Sampler
>>> sampler = Sampler(num_items=5, normalised_capacity=0.6)
>>> knapsack = sampler.sample()
>>> len(knapsack.items)
5
Create a sampler with custom distributions:
>>> import numpy as np
>>> sampler = Sampler(
...     num_items=5,
...     normalised_capacity=(0.5, 0.8),
...     weight_dist="normal",
...     weight_dist_kwargs={"loc": 100, "scale": 10},
...     value_dist="normal",
...     value_dist_kwargs={"loc": 50, "scale": 5},
... )
>>> knapsack = sampler.sample()
>>> len(knapsack.items)
5