/
Packer.php
324 lines (281 loc) · 8.91 KB
/
Packer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
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
<?php
/**
* Box packing (3D bin packing, knapsack problem).
*
* @author Doug Wright
*/
namespace DVDoug\BoxPacker;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LogLevel;
use Psr\Log\NullLogger;
/**
* Actual packer.
*
* @author Doug Wright
*/
class Packer implements LoggerAwareInterface
{
use LoggerAwareTrait;
/**
* Number of boxes at which balancing weight is deemed not worth it.
*
* @var int
*/
protected $maxBoxesToBalanceWeight = 12;
/**
* List of items to be packed.
*
* @var ItemList
*/
protected $items;
/**
* List of box sizes available to pack items into.
*
* @var BoxList
*/
protected $boxes;
/**
* Constructor.
*/
public function __construct()
{
$this->items = new ItemList();
$this->boxes = new BoxList();
$this->logger = new NullLogger();
}
/**
* Add item to be packed.
*
* @param Item $item
* @param int $qty
*/
public function addItem(Item $item, $qty = 1)
{
for ($i = 0; $i < $qty; ++$i) {
$this->items->insert($item);
}
$this->logger->log(LogLevel::INFO, "added {$qty} x {$item->getDescription()}", ['item' => $item]);
}
/**
* Set a list of items all at once.
*
* @param iterable|Item[] $items
*/
public function setItems($items)
{
if ($items instanceof ItemList) {
$this->items = clone $items;
} else {
$this->items = new ItemList();
foreach ($items as $item) {
$this->items->insert($item);
}
}
}
/**
* Add box size.
*
* @param Box $box
*/
public function addBox(Box $box)
{
$this->boxes->insert($box);
$this->logger->log(LogLevel::INFO, "added box {$box->getReference()}", ['box' => $box]);
}
/**
* Add a pre-prepared set of boxes all at once.
*
* @param BoxList $boxList
*/
public function setBoxes(BoxList $boxList)
{
$this->boxes = clone $boxList;
}
/**
* Number of boxes at which balancing weight is deemed not worth the extra computation time.
*
* @return int
*/
public function getMaxBoxesToBalanceWeight()
{
return $this->maxBoxesToBalanceWeight;
}
/**
* Number of boxes at which balancing weight is deemed not worth the extra computation time.
*
* @param int $maxBoxesToBalanceWeight
*/
public function setMaxBoxesToBalanceWeight($maxBoxesToBalanceWeight)
{
$this->maxBoxesToBalanceWeight = $maxBoxesToBalanceWeight;
}
/**
* Pack items into boxes.
*
* @return PackedBoxList
*/
public function pack()
{
$this->sanityPrecheck();
$packedBoxes = $this->doVolumePacking();
//If we have multiple boxes, try and optimise/even-out weight distribution
if ($packedBoxes->count() > 1 && $packedBoxes->count() <= $this->maxBoxesToBalanceWeight) {
$redistributor = new WeightRedistributor($this->boxes);
$redistributor->setLogger($this->logger);
$packedBoxes = $redistributor->redistributeWeight($packedBoxes);
}
$this->logger->log(LogLevel::INFO, "[PACKING COMPLETED], {$packedBoxes->count()} boxes");
return $packedBoxes;
}
/**
* Pack items into boxes using the principle of largest volume item first.
*
* @throws NoBoxesAvailableException
*
* @return PackedBoxList
*/
public function doVolumePacking($singlePassMode = false, $enforceSingleBox = false)
{
$packedBoxes = new PackedBoxList();
//Keep going until everything packed
while ($this->items->count()) {
$packedBoxesIteration = [];
//Loop through boxes starting with smallest, see what happens
foreach ($this->getBoxList($enforceSingleBox) as $box) {
$volumePacker = new VolumePacker($box, $this->items);
$volumePacker->setLogger($this->logger);
$volumePacker->setSinglePassMode($singlePassMode);
$packedBox = $volumePacker->pack();
if ($packedBox->getItems()->count()) {
$packedBoxesIteration[] = $packedBox;
//Have we found a single box that contains everything?
if ($packedBox->getItems()->count() === $this->items->count()) {
break;
}
}
}
try {
//Find best box of iteration, and remove packed items from unpacked list
$bestBox = $this->findBestBoxFromIteration($packedBoxesIteration);
} catch (NoBoxesAvailableException $e) {
if ($enforceSingleBox) {
return new PackedBoxList();
}
throw $e;
}
$this->items->removePackedItems($bestBox->getPackedItems());
$packedBoxes->insert($bestBox);
}
return $packedBoxes;
}
/**
* Get a "smart" ordering of the boxes to try packing items into. The initial BoxList is already sorted in order
* so that the smallest boxes are evaluated first, but this means that time is spent on boxes that cannot possibly
* hold the entire set of items due to volume limitations. These should be evaluated first.
*/
protected function getBoxList($enforceSingleBox = false)
{
$itemVolume = 0;
foreach (clone $this->items as $item) {
$itemVolume += $item->getWidth() * $item->getLength() * $item->getDepth();
}
$preferredBoxes = [];
$otherBoxes = [];
foreach (clone $this->boxes as $box) {
if ($box->getInnerWidth() * $box->getInnerLength() * $box->getInnerDepth() >= $itemVolume) {
$preferredBoxes[] = $box;
} elseif (!$enforceSingleBox) {
$otherBoxes[] = $box;
}
}
return array_merge($preferredBoxes, $otherBoxes);
}
/**
* @param PackedBox[] $packedBoxes
*/
protected function findBestBoxFromIteration(array $packedBoxes)
{
if (count($packedBoxes) === 0) {
throw new NoBoxesAvailableException("No boxes could be found for item '{$this->items->top()->getDescription()}'", $this->items->top());
}
usort($packedBoxes, [$this, 'compare']);
return $packedBoxes[0];
}
private function sanityPrecheck()
{
/** @var Item $item */
foreach (clone $this->items as $item) {
$possibleFits = 0;
/** @var Box $box */
foreach (clone $this->boxes as $box) {
if ($item->getWeight() <= ($box->getMaxWeight() - $box->getEmptyWeight())) {
$possibleFits += count((new OrientatedItemFactory($box))->getPossibleOrientationsInEmptyBox($item));
}
}
if ($possibleFits === 0) {
throw new ItemTooLargeException("Item '{$item->getDescription()}' is too large to fit into any box", $item);
}
}
}
private static function compare(PackedBox $boxA, PackedBox $boxB)
{
$choice = $boxB->getItems()->count() - $boxA->getItems()->count();
if ($choice == 0) {
$choice = $boxB->getVolumeUtilisation() - $boxA->getVolumeUtilisation();
}
if ($choice == 0) {
$choice = $boxB->getUsedVolume() - $boxA->getUsedVolume();
}
if ($choice == 0) {
$choice = PHP_MAJOR_VERSION > 5 ? -1 : 1;
}
return $choice;
}
/**
* Pack as many items as possible into specific given box.
*
* @deprecated
*
* @param Box $box
* @param ItemList $items
*
* @return PackedBox packed box
*/
public function packIntoBox(Box $box, ItemList $items)
{
$volumePacker = new VolumePacker($box, clone $items);
$volumePacker->setLogger($this->logger);
return $volumePacker->pack();
}
/**
* Pack as many items as possible into specific given box.
*
* @deprecated
*
* @param Box $box
* @param ItemList $items
*
* @return ItemList items packed into box
*/
public function packBox(Box $box, ItemList $items)
{
$packedBox = $this->packIntoBox($box, $items);
return $packedBox->getItems();
}
/**
* Given a solution set of packed boxes, repack them to achieve optimum weight distribution.
*
* @deprecated
*
* @param PackedBoxList $originalBoxes
*
* @return PackedBoxList
*/
public function redistributeWeight(PackedBoxList $originalBoxes)
{
$redistributor = new WeightRedistributor($this->boxes);
$redistributor->setLogger($this->logger);
return $redistributor->redistributeWeight($originalBoxes);
}
}