Passed
Push — 2.x-dev ( eccc16...ab1c97 )
by Doug
07:42
created

Packer::compare()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

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