241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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 | class BPPDomain(Domain):
capacity_approaches = Literal["evolved", "percentage", "fixed"]
def __init__(
self,
number_of_items: np.uint32 | int = 50,
minimum_weight: np.uint32 = np.uint32(1),
maximum_weight: np.uint32 = np.uint32(1_000),
maximum_capacity: np.uint32 = np.uint32(100),
capacity_approach: capacity_approaches = "fixed",
capacity_ratio: float = 0.8,
seed: Optional[int | np.random.SeedSequence] = None,
):
"""Bin Packing Problem Domain
Creates a new domain to generate instances for the Bin Packing Problem (BPP).
Args:
number_of_items (np.uint32 | int, optional): Number of items that the instance must contain. Defaults to 50.
minimum_weight (np.uint32 | int, optional): Minimum value of each item. ç
This is the lowest weight that an item can have. Defaults to np.uint32(1).
maximum_weight (np.uint32, optional): Maximum value of each item. This is the highest
weight that an item can have. Defaults to np.uint32(1_000).
maximum_capacity (np.uint32, optional): Maximum capacity of each bin in the instance.
Defaults to np.uint32(100).
capacity_approach (capacity_approaches, optional): Literal to define how the capacities
of the instances will be computed. If fixed, the capacity is defined as the
maximum_capacity value. If evolved, the capacity can be updated during the evolution,
and finally if `percentage` the capacity is defined as capacity_ratio * capacity
during the evolution. Defaults to "fixed".
capacity_ratio (float, optional): Capacity ratio used when the capacity_approach is set
to percentage. It must be a float value in the range (0.0, 1.0]. Defaults to 0.8.
seed (Optional[int | np.random.SeedSequence], optional): Seed for the random number engine. Defaults to None.
Raises:
ValueError: If the minimum_weight or maximum_weight are negative
ValueError: If the minimum_weight > maximum_weight
ValueError: If the maximum_capacity is not a valid integer, or it's <= 0
ValueError: If the capacity_approach is not available
ValueError: If the capacity_ratio is not a float or it's outside the range (0.0, 1.0]
"""
try:
self.number_of_items = int(number_of_items)
if self.number_of_items <= 0:
raise ValueError(
"number_of_items must be a "
"postive integer in BPPDomain. "
f"Got: {number_of_items}"
)
except (TypeError, ValueError) as exc:
raise ValueError from exc
try:
self._minimum_weight = int(minimum_weight)
self._maximum_weight = int(maximum_weight)
# If we have negative bounds or min > max raise ValueError
if (
minimum_weight < 0
or maximum_weight < 0
or minimum_weight > maximum_weight
):
raise ValueError()
except (TypeError, ValueError) as exc:
raise ValueError(
"Invalid min_i and/or max_i in BPPDomain."
f"Expected min_i ({minimum_weight}) to be >= 0 and < max_i ({maximum_weight}) "
f"and max_i to be >= 0."
) from exc
try:
self._max_capacity = int(maximum_capacity)
self._capacity_ratio = float(capacity_ratio)
if maximum_capacity <= 0:
raise ValueError("invalid max_capacity value")
if self._capacity_ratio <= 0 or self._capacity_ratio > 1:
raise ValueError("invalid capacity_ratio value")
except (TypeError, ValueError) as exc:
raise ValueError(
"Invalid maximum capacity and/or capacity ratio for BPPDomain. "
f"Capacity ({maximum_capacity}) was expected to be a positive integer, "
f"and capacity_ratio ({capacity_ratio}) must be a float in the range (0.0, 1.0]."
) from exc
if capacity_approach not in self.capacity_approaches.__args__:
invalid_approach_msg = (
f"The capacity approach {capacity_approach} is not available. "
f" Please, consider choosing between {self.capacity_approaches.__args__}. "
f" Set `evolved` approach set as fallback."
)
warnings.warn(invalid_approach_msg, RuntimeWarning)
self._capacity_approach = "fixed"
else:
self._capacity_approach = capacity_approach
bounds = [(1.0, self._max_capacity)] + [
(self._minimum_weight, self._maximum_weight) for _ in range(number_of_items)
]
features_names = "mean,std,median,max,min,tiny,small,medium,large,huge".split(
","
)
super().__init__(
dimension=self.number_of_items + 1,
bounds=bounds,
domain_name="BPP",
features_names=features_names,
seed=seed,
)
@property
def capacity_approach(self):
return self._capacity_approach
@property
def capacity_ratio(self):
if self._capacity_approach == "percentage":
return self._capacity_ratio
else:
return 1.0
@property
def maximum_capacity(self) -> int:
return self._max_capacity
@property
def minimum_weight(self) -> int:
return self._minimum_weight
@property
def maximum_weight(self) -> int:
return self._maximum_weight
def generate_instances(self, n: np.uint32 = np.uint32(1)) -> Sequence[Instance]:
"""Generates N new instances for the BPP domain.
Args:
n (int, optional): Number of instances to generate. Defaults to 1.
Returns:
List[Instance]: A list of Instance objects created from the raw numpy generation
"""
# Dimension is set correctly to number_of_items + 1 to
# allow the random generation of capacities
instances = self._rng.integers(
low=self._minimum_weight,
high=self._maximum_weight,
size=(n, self._dimension),
dtype=int,
)
# Sets the capacity according to the method
match self.capacity_approach:
case "evolved":
instances[:, 0] = self._rng.integers(1, self._max_capacity, size=n)
case "percentage":
instances[:, 0] = (
np.sum(instances[:, 1:], axis=1, dtype=np.int32)
* self._capacity_ratio
)
case "fixed":
instances[:, 0] = self._max_capacity
return list(Instance(variables=i) for i in instances)
def extract_features(
self, instances: Sequence[Instance] | np.ndarray
) -> np.ndarray:
"""Extract the features of the instance based on the BPP domain.
For the BPP domain, the features consist of:
- N as the number of items,
- Capacity as the maximum capacity of each bin, MeanWeights of the items,
- MedianWeights of the items, VarianceWeights of the weights of the items,
- MaxWeight of the items in the instance, MinWeight of the items,
- Huge as the ratio of items with normalised weights > 0.5,
- Large as the ratio of items with normalised weights between 0.333 and 0.5,
- Medium as the ratio of items with normalised weights between 0.25 and 0.333,
- Small as the ratio of items with normalised weights >= 0.25,
- Tiny as the ratio of items with normalised weights >= 0.1
Args:
instances (Instance): Instances to extract the features from
Returns:
np.ndarray: Values of each feature
"""
if not isinstance(instances, np.ndarray):
instances = np.asarray(instances)
norm_variables = np.asarray(instances, copy=True, dtype=np.float64)
norm_variables[:, 1:] = norm_variables[:, 1:] / norm_variables[:, 0:1]
huge = 0.5
medium = 0.33333
large = 0.25
tiny = 0.1
return np.column_stack(
[
np.mean(norm_variables, axis=1),
np.std(norm_variables, axis=1),
np.median(norm_variables, axis=1),
np.max(norm_variables, axis=1),
np.min(norm_variables, axis=1),
np.mean(norm_variables > huge, axis=1), # Huge
np.mean((huge >= norm_variables) & (norm_variables > medium), axis=1),
np.mean((medium >= norm_variables) & (norm_variables > large), axis=1),
np.mean(large >= norm_variables, axis=1), # Small
np.mean(tiny >= norm_variables, axis=1), # Tiny
],
).astype(np.float64)
def extract_features_as_dict(
self, instances: Sequence[Instance] | np.ndarray
) -> List[Dict[str, np.float64]]:
"""Creates a dictionary with the features of the instances.
The key are the names of each feature and the values are
the values extracted from instance.
For the BPP domain, the features consist of:
- N as the number of items,
- Capacity as the maximum capacity of each bin, MeanWeights of the items,
- MedianWeights of the items, VarianceWeights of the weights of the items,
- MaxWeight of the items in the instance, MinWeight of the items,
- Huge as the ratio of items with normalised weights > 0.5,
- Large as the ratio of items with normalised weights between 0.333 and 0.5,
- Medium as the ratio of items with normalised weights between 0.25 and 0.333,
- Small as the ratio of items with normalised weights >= 0.25,
- Tiny as the ratio of items with normalised weights >= 0.1
Args:
instances (Sequence[Instance]): Instances to extract the features from.
Returns:
Dict[str, np.float64]: Dictionary with the names/values of each feature
"""
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[BPP]:
"""Generates BPP problems from the given instances
This method is used to generate a collection of (objects)
of the BPP class ready to be solved from the definition of the instances.
Args:
instances (Sequence[Instance] | np.ndarray): Instances to generate
the problems from.
Returns:
List[BPP]: List of BPP objects created from the instances
"""
if not isinstance(instances, np.ndarray):
instances = np.asarray(instances)
# Assume evolved capacities
capacities = instances[:, 0].astype(np.int32)
match self.capacity_approach:
case "percentage":
capacities[:] = (
np.sum(instances[:, 1:], axis=1) * self._capacity_ratio
).astype(np.int32)
instances[:, 0] = capacities[:]
case "fixed":
capacities[:] = self._max_capacity
instances[:, 0] = self._max_capacity
# The first item of each valid BPP instance is the capacity
print(capacities)
return list(
BPP(items=instances[i, 1:], maximum_capacity=capacities[i])
for i in range(len(instances))
)
|