259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541 | class KnapsackDomain(Domain):
"""Knapsack Domain for synthesizing Knapsack Problem instances.
This class allows to create benchmark instances by sampling
item weights and profits and then assigning a capacity using one of several strategies.
Note that the number of dimensions defined produces instances of N = dimension items.
Which means that the results Instance objects will have 2 * dimension + 1 variables:
- Q, w_0, p_0, w_1, p_1, ..., w_N-1, p_N-1
It also provides utilities to extract descriptive features
and build concrete Knapsack problems from the generated data.
"""
capacity_approaches = Literal["evolved", "percentage", "fixed"]
def __init__(
self,
number_of_items: np.uint32 | int = np.uint32(50),
minimum_weight: np.uint32 = np.uint32(1),
maximum_weight: np.uint32 = np.uint32(1_000),
minimum_profit: np.uint32 = np.uint32(1),
maximum_profit: np.uint32 = np.uint32(1_000),
maximum_capacity: np.uint32 = np.uint32(1e5),
capacity_approach: str = "evolved",
capacity_ratio: float = 0.8,
seed: Optional[int | np.random.SeedSequence] = None,
):
"""Create a domain that can generate knapsack instances with configurable difficulty.
Args:
number_of_items (np.uint32, optional): Number of items in each generated instance. Note that
the dimension of the domain will be calculated as 2 * number_of_items + 1. Defaults to 50.
minimum_weight (np.uint32, optional): Lower bound for the weight of each item. Defaults to 1.
maximum_weight (np.uint32, optional): Upper bound for the weight of each item. Defaults to 1,000.
minimum_profit (np.uint32, optional): Lower bound for the profit of each item. Defaults to 1.
maximum_profit (np.uint32, optional): Upper bound for the profit of each item. Defaults to 1,000.
maximum_capacity (np.uint32, optional): Maximum capacity that can be assigned to a
Knapsack instance when using the evolved or fixed strategy. Defaults to 100,000.
capacity_approach (str, optional): Strategy used to assign capacities to generated instances. Defaults to evolved.
capacity_ratio (float, optional): Ratio used to derive the capacity when the percentage strategy is selected. Defaults to 0.8.
seed (Optional[int | np.random.SeedSequence], optional): Seed used to initialize the random generator. Default to None.
"""
try:
self._number_of_items = int(number_of_items)
if number_of_items <= 0:
raise ValueError()
except (TypeError, ValueError) as exc:
raise ValueError(
f"invalid dimension for KnapsackDomain. Got: {number_of_items}"
) from exc
try:
self._minimum_profit = int(minimum_profit)
self._minimum_weight = int(minimum_weight)
self._maximum_profit = int(maximum_profit)
self._maximum_weight = int(maximum_weight)
self._maximum_capacity = int(maximum_capacity)
if self._maximum_capacity <= 0:
raise ValueError(
f"maximum_capacity cannot be negative: {self._maximum_capacity}"
)
if (
self._minimum_profit <= 0
or self._maximum_profit <= 0
or self._minimum_profit >= self._maximum_profit
):
raise ValueError(
f"error in profit ranges: ({self._minimum_profit}, {self._maximum_profit})"
)
if (
self._minimum_weight <= 0
or self._minimum_weight <= 0
or self._minimum_weight >= self._maximum_weight
):
raise ValueError(
f"error in weight ranges: ({self._minimum_weight}, {self._maximum_weight})"
)
except (TypeError, ValueError) as exc:
raise ValueError(
"capacity, minimum and maximum ranges must be valid positive integers. "
f"Expects capacity ({maximum_capacity}). "
f"Expects minimum_profit ({minimum_profit}) to be greater "
f"than zero and less than maximum_profit ({maximum_profit}).\n"
f"Expects minimum_weight ({minimum_weight}) to be greater "
f"than zero and less than maximum_weight ({maximum_weight}).\n"
) from exc
try:
self._capacity_ratio = float(capacity_ratio)
if self._capacity_ratio <= 0 or self._capacity_ratio > 1:
raise ValueError(
"capacity_ratio must be a positive float in the range [0.0, 1.0]."
)
except (TypeError, ValueError) as exc:
raise ValueError from exc
if capacity_approach not in self.capacity_approaches.__args__:
warnings.warn(
f"The capacity approach {capacity_approach} is not available. "
f"Please, consider choosing from {self.capacity_approaches.__args__}. "
"Set evolved approach set as fallback.",
RuntimeWarning,
)
self._capacity_approach = "evolved"
else:
self._capacity_approach = capacity_approach
_bounds = [(1.0, self._maximum_capacity)] + [
(minimum_weight, maximum_weight)
if i % 2 == 0
else (minimum_profit, maximum_profit)
for i in range(number_of_items * 2) # Remove the capacity dimension
]
_features_names = "capacity,max_p,max_w,min_p,min_w,avg_eff,mean,std".split(",")
# The dimension of a KnapsackDomain is 2 times number of items plus the capacity
_dimension = (self._number_of_items * 2) + 1
super().__init__(
dimension=_dimension,
bounds=_bounds,
domain_name="Knapsack",
features_names=_features_names,
seed=seed,
)
@property
def capacity_approach(self):
"""Return the strategy currently used to assign capacities to generated instances."""
return self._capacity_approach
@property
def capacity_ratio(self):
"""Returns the ratio to which the capacity is update when using percentage approach"""
return self._capacity_ratio
def generate_instances(self, n: np.uint32 | int = np.uint32(1)) -> List[Instance]:
"""Generate a batch of knapsack instances.
The method samples item weights and profits for each instance and then assigns a
capacity according to the selected strategy. This creates instances with varying
levels of difficulty and tightness.
Args:
n (int, optional): Number of instances to generate. Defaults to 1.
Returns:
List[Instance]: A list of generated instance objects.
"""
weights_and_profits = np.empty(
shape=(n, self._number_of_items * 2), dtype=np.uint32
)
weights_and_profits[:, 0::2] = self._rng.integers(
low=self._minimum_weight,
high=self._maximum_weight,
size=(n, self._number_of_items),
)
weights_and_profits[:, 1::2] = self._rng.integers(
low=self._minimum_profit,
high=self._maximum_profit,
size=(n, self._number_of_items),
)
# Assume fixed
capacities = np.full(n, fill_value=self._maximum_capacity, dtype=np.int32)
match self.capacity_approach:
case "evolved":
capacities[:] = self._rng.integers(1, self._maximum_capacity, size=n)
case "percentage":
capacities[:] = (
np.sum(weights_and_profits[:, 1::2], axis=1) * self.capacity_ratio
).astype(np.int32)
return list(
Instance(i) for i in np.column_stack((capacities, weights_and_profits))
)
def extract_features(
self, instances: Sequence[Instance] | np.ndarray
) -> np.ndarray:
"""Compute a compact set of numerical features for the supplied instances.
These features summarize the Knapsack instance structure, they include:
- Capacity
- Maximum profit
- Maximum weight
- Minimum profit
- Minimum weight
- Average efficiency as the average ratio of profits / weights
- Mean of the values (both profits and weights)
- Standard deviation of the values (both profits and weights)
Args:
instances (Sequence[Instance]): Instances to characterize.
Returns:
np.ndarray: A two-dimensional array where each row contains the features of one instance.
"""
_instances = np.asarray(instances)
features = np.empty(shape=(len(_instances), 8), dtype=np.float64)
weights = _instances[:, 1::2]
profits = _instances[:, 2::2]
efficiency = np.mean(profits / weights, axis=1, dtype=np.float64)
features[:, 0] = _instances[:, 0] # Qs
features[:, 1] = np.max(profits, axis=1)
features[:, 2] = np.max(weights, axis=1)
features[:, 3] = np.min(profits, axis=1)
features[:, 4] = np.min(weights, axis=1)
features[:, 5] = efficiency
features[:, 6] = np.mean(_instances[:, 1:], axis=1)
features[:, 7] = np.std(_instances[:, 1:], axis=1)
return features
def extract_features_as_dict(
self, instances: Sequence[Instance] | np.ndarray
) -> List[Dict[str, np.float64]]:
"""Return the extracted features as dictionaries.
These features summarize the Knapsack instance structure, they include:
- Capacity
- Maximum profit
- Maximum weight
- Minimum profit
- Minimum weight
- Average efficiency as the average ratio of profits / weights
- Mean of the values (both profits and weights)
- Standard deviation of the values (both profits and weights)
Args:
instances (Sequence[Instance]): Instances whose features should be extracted.
Returns:
List[Dict[str, np.float64]]: One dictionary per instance containing the named features.
"""
features = self.extract_features(instances)
named_features = []
for instance_features in features:
named_features.append({
k: v for k, v in zip(self.features_names, instance_features)
})
return named_features
def generate_problems_from_instances(
self, instances: Sequence[Instance] | np.ndarray
) -> List:
"""Create Knapsack Problem objects from the given instances.
This method converts the numerical representation of each instance into a fully
functional Knapsack Problem that can be passed directly to a solver.
Args:
instances (Sequence[Instance]): Instances to transform into problems.
Returns:
List: A list containing one Knapsack problem per instance.
"""
_instances = np.asarray(instances)
capacities = _instances[:, 0].astype(np.int32)
weights = _instances[:, 1::2].astype(np.uint32)
profits = _instances[:, 2::2].astype(np.uint32)
# Sets the capacity according to the method
if self.capacity_approach == "percentage":
capacities[:] = (np.sum(weights, axis=1) * self.capacity_ratio).astype(
np.int32
)
_instances[:, 0] = capacities[:]
elif self.capacity_approach == "fixed":
capacities[:] = self._maximum_capacity
_instances[:, 0] = capacities[:]
return list(
Knapsack(profits=profits[i], weights=weights[i], capacity=capacities[i])
for i in range(len(_instances))
)
|