Passed
Push — 3.x ( 9491a9...361ba2 )
by Doug
01:29
created

Packer::setMaxBoxesToBalanceWeight()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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