Test Failed
Pull Request — master (#198)
by
unknown
12:34 queued 04:39
created

Packer::pack()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 2
nop 0
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 3
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 27
    public function __construct()
60
    {
61 27
        $this->items = new ItemList();
62 27
        $this->boxes = new BoxList();
63 27
        $this->boxesQtyAvailable = new SplObjectStorage();
64
65 27
        $this->logger = new NullLogger();
66 27
    }
67
68
    /**
69
     * Add item to be packed.
70
     */
71 19
    public function addItem(Item $item, int $qty = 1): void
72
    {
73 19
        for ($i = 0; $i < $qty; ++$i) {
74 19
            $this->items->insert($item);
75
        }
76 19
        $this->logger->log(LogLevel::INFO, "added {$qty} x {$item->getDescription()}", ['item' => $item]);
77 19
    }
78
79
    /**
80
     * Set a list of items all at once.
81
     */
82 12
    public function setItems(iterable $items): void
83
    {
84 12
        if ($items instanceof ItemList) {
85 8
            $this->items = clone $items;
86
        } else {
87 4
            $this->items = new ItemList();
88 4
            foreach ($items as $item) {
89 4
                $this->items->insert($item);
90
            }
91
        }
92 12
    }
93
94
    /**
95
     * Add box size.
96
     */
97 18
    public function addBox(Box $box): void
98
    {
99 18
        $this->boxes->insert($box);
100 18
        $this->setBoxQuantity($box, $box instanceof LimitedSupplyBox ? $box->getQuantityAvailable() : PHP_INT_MAX);
101 18
        $this->logger->log(LogLevel::INFO, "added box {$box->getReference()}", ['box' => $box]);
102 18
    }
103
104
    /**
105
     * Add a pre-prepared set of boxes all at once.
106
     */
107 11
    public function setBoxes(BoxList $boxList): void
108
    {
109 11
        $this->boxes = $boxList;
110 11
        foreach ($this->boxes as $box) {
111 11
            $this->setBoxQuantity($box, $box instanceof LimitedSupplyBox ? $box->getQuantityAvailable() : PHP_INT_MAX);
112
        }
113 11
    }
114
115
    /**
116
     * Set the quantity of this box type available.
117
     */
118 25
    public function setBoxQuantity(Box $box, int $qty): void
119
    {
120 25
        $this->boxesQtyAvailable[$box] = $qty;
121 25
    }
122
123
    /**
124
     * Number of boxes at which balancing weight is deemed not worth the extra computation time.
125
     */
126 1
    public function getMaxBoxesToBalanceWeight(): int
127
    {
128 1
        return $this->maxBoxesToBalanceWeight;
129
    }
130
131
    /**
132
     * Number of boxes at which balancing weight is deemed not worth the extra computation time.
133
     */
134 1
    public function setMaxBoxesToBalanceWeight(int $maxBoxesToBalanceWeight): void
135
    {
136 1
        $this->maxBoxesToBalanceWeight = $maxBoxesToBalanceWeight;
137 1
    }
138
139
    /**
140
     * Pack items into boxes.
141
     */
142 26
    public function pack(): PackedBoxList
143
    {
144 26
        $this->sanityPrecheck();
145 24
        $packedBoxes = $this->doVolumePacking();
146
147
        //If we have multiple boxes, try and optimise/even-out weight distribution
148 23
        if ($packedBoxes->count() > 1 && $packedBoxes->count() <= $this->maxBoxesToBalanceWeight) {
149 10
            $redistributor = new WeightRedistributor($this->boxes, $this->boxesQtyAvailable);
150 10
            $redistributor->setLogger($this->logger);
151 10
            $packedBoxes = $redistributor->redistributeWeight($packedBoxes);
152
        }
153
154 23
        $this->logger->log(LogLevel::INFO, "[PACKING COMPLETED], {$packedBoxes->count()} boxes");
155
156 23
        return $packedBoxes;
157
    }
158
159
    /**
160
     * Pack items into boxes using the principle of largest volume item first.
161
     *
162
     * @throws NoBoxesAvailableException
163
     */
164 24
    public function doVolumePacking(): PackedBoxList
165
    {
166 24
        $packedBoxes = new PackedBoxList();
167
168
        //Keep going until everything packed
169 24
        while ($this->items->count()) {
170 23
            $packedBoxesIteration = [];
171
172
            //Loop through boxes starting with smallest, see what happens
173 23
            foreach ($this->boxes as $box) {
174 23
                if ($this->boxesQtyAvailable[$box] > 0) {
175 23
                    $volumePacker = new VolumePacker($box, $this->items);
176 23
                    $volumePacker->setLogger($this->logger);
177 23
                    $packedBox = $volumePacker->pack();
178 23
                    if ($packedBox->getItems()->count()) {
179 23
                        $packedBoxesIteration[] = $packedBox;
180
181
                        //Have we found a single box that contains everything?
182 23
                        if ($packedBox->getItems()->count() === $this->items->count()) {
183 22
                            break;
184
                        }
185
                    }
186
                }
187
            }
188
189
            //Find best box of iteration, and remove packed items from unpacked list
190 23
            $bestBox = $this->findBestBoxFromIteration($packedBoxesIteration);
191
192
            /** @var PackedItem $packedItem */
193 23
            foreach ($bestBox->getItems() as $packedItem) {
194 23
                $this->items->remove($packedItem->getItem());
195
            }
196
197 23
            $packedBoxes->insert($bestBox);
198 23
            $this->boxesQtyAvailable[$bestBox->getBox()] = $this->boxesQtyAvailable[$bestBox->getBox()] - 1;
199
        }
200
201 23
        return $packedBoxes;
202
    }
203
204
    /**
205
     * Pack all items into a single box if possible, otherwise return an empty list
206
     *
207
     * @throws NoBoxesAvailableException
208
     */
209 4
    public function doVolumePackingSingleBox(): PackedBoxList
210
    {
211 4
        $packedBoxes = new PackedBoxList();
212 4
        $itemsTotalVolume = $this->items->getTotalVolume();
213
214
        // Find smallest box that will hold all items
215 4
        foreach ($this->boxes as $box) {
216
            // Skip boxes that are not available
217 4
            if ($this->boxesQtyAvailable[$box] < 1) {
218
                continue;
219
            }
220
221
            // Skip boxes that are obviously too small
222 4
            if ($box->getInnerDepth() * $box->getInnerLength() * $box->getInnerWidth() < $itemsTotalVolume) {
223 2
                continue;
224
            }
225
226
            // Attempt to pack all items into one box
227 2
            $volumePacker = new VolumePacker($box, $this->items);
228 2
            $volumePacker->setLogger($this->logger);
229 2
            $packedBox = $volumePacker->pack();
230 2
            if ($packedBox->getItems()->count() < $this->items->count()) {
231 1
                $packedBoxes->insert($packedBox);
232 1
                $this->boxesQtyAvailable[$packedBox->getBox()] = $this->boxesQtyAvailable[$packedBox->getBox()] - 1;
233 1
                break;
234
            }
235
        }
236
237 4
        return $packedBoxes;
238
    }
239
240
    /**
241
     * @param PackedBox[] $packedBoxes
242
     */
243 23
    protected function findBestBoxFromIteration(array $packedBoxes): PackedBox
244
    {
245 23
        if (count($packedBoxes) === 0) {
246 1
            throw new NoBoxesAvailableException("No boxes could be found for item '{$this->items->top()->getDescription()}'", $this->items->top());
247
        }
248
249 23
        usort($packedBoxes, [$this, 'compare']);
250
251 23
        return $packedBoxes[0];
252
    }
253
254 26
    private function sanityPrecheck(): void
255
    {
256
        /** @var Item $item */
257 26
        foreach ($this->items as $item) {
258 26
            $possibleFits = 0;
259
260
            /** @var Box $box */
261 26
            foreach ($this->boxes as $box) {
262 25
                if ($item->getWeight() <= ($box->getMaxWeight() - $box->getEmptyWeight())) {
263 25
                    $possibleFits += count((new OrientatedItemFactory($box))->getPossibleOrientationsInEmptyBox($item));
264
                }
265
            }
266
267 26
            if ($possibleFits === 0) {
268 5
                throw new ItemTooLargeException("Item '{$item->getDescription()}' is too large to fit into any box", $item);
269
            }
270
        }
271 24
    }
272
273 7
    private static function compare(PackedBox $boxA, PackedBox $boxB): int
274
    {
275 7
        $choice = $boxB->getItems()->count() <=> $boxA->getItems()->count();
276
277 7
        if ($choice === 0) {
278 4
            $choice = $boxB->getVolumeUtilisation() <=> $boxA->getVolumeUtilisation();
279
        }
280 7
        if ($choice === 0) {
281 3
            $choice = $boxB->getUsedVolume() <=> $boxA->getUsedVolume();
282
        }
283
284 7
        return $choice;
285
    }
286
}
287