Passed
Push — 3.x ( f78397...42dd24 )
by Doug
09:29
created

WeightRedistributor::redistributeWeight()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 37
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 20
c 2
b 0
f 0
nc 5
nop 1
dl 0
loc 37
ccs 19
cts 19
cp 1
crap 7
rs 8.6666
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 array_filter;
12
use function array_map;
13
use function array_merge;
14
use function array_sum;
15
use function count;
16
use function iterator_to_array;
17
use Psr\Log\LoggerAwareInterface;
18
use Psr\Log\LoggerAwareTrait;
19
use Psr\Log\LogLevel;
20
use Psr\Log\NullLogger;
21
use SplObjectStorage;
22
use function usort;
23
24
/**
25
 * Actual packer.
26
 *
27
 * @author Doug Wright
28
 * @internal
29
 */
30
class WeightRedistributor implements LoggerAwareInterface
31
{
32
    use LoggerAwareTrait;
33
34
    /**
35
     * List of box sizes available to pack items into.
36
     *
37
     * @var BoxList
38
     */
39
    private $boxes;
40
41
    /**
42
     * Quantities available of each box type.
43
     *
44
     * @var SplObjectStorage|int[]
45
     */
46
    private $boxesQtyAvailable;
47
48
    /**
49
     * @var PackedBoxSorter
50
     */
51
    private $packedBoxSorter;
52
53
    /**
54
     * Constructor.
55
     */
56 15
    public function __construct(BoxList $boxList, PackedBoxSorter $packedBoxSorter, SplObjectStorage $boxQuantitiesAvailable)
57
    {
58 15
        $this->boxes = $boxList;
59 15
        $this->packedBoxSorter = $packedBoxSorter;
60 15
        $this->boxesQtyAvailable = $boxQuantitiesAvailable;
61 15
        $this->logger = new NullLogger();
62
    }
63
64
    /**
65
     * Given a solution set of packed boxes, repack them to achieve optimum weight distribution.
66
     */
67 15
    public function redistributeWeight(PackedBoxList $originalBoxes): PackedBoxList
68
    {
69 15
        $targetWeight = $originalBoxes->getMeanItemWeight();
70 15
        $this->logger->log(LogLevel::DEBUG, "repacking for weight distribution, weight variance {$originalBoxes->getWeightVariance()}, target weight {$targetWeight}");
0 ignored issues
show
Bug introduced by
The method log() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

70
        $this->logger->/** @scrutinizer ignore-call */ 
71
                       log(LogLevel::DEBUG, "repacking for weight distribution, weight variance {$originalBoxes->getWeightVariance()}, target weight {$targetWeight}");

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
71
72
        /** @var PackedBox[] $boxes */
73 15
        $boxes = iterator_to_array($originalBoxes);
74
75 15
        usort($boxes, static function (PackedBox $boxA, PackedBox $boxB) {
76 15
            return $boxB->getWeight() <=> $boxA->getWeight();
77
        });
78
79
        do {
80 15
            $iterationSuccessful = false;
81
82 15
            foreach ($boxes as $a => &$boxA) {
83 15
                foreach ($boxes as $b => &$boxB) {
84 15
                    if ($b <= $a || $boxA->getWeight() === $boxB->getWeight()) {
85 15
                        continue; // no need to evaluate
86
                    }
87
88 10
                    $iterationSuccessful = $this->equaliseWeight($boxA, $boxB, $targetWeight);
89 10
                    if ($iterationSuccessful) {
90 5
                        $boxes = array_filter($boxes, static function (?PackedBox $box) { // remove any now-empty boxes from the list
91 5
                            return $box instanceof PackedBox;
92
                        });
93 5
                        break 2;
94
                    }
95
                }
96
            }
97
        } while ($iterationSuccessful);
98
99
        // Combine back into a single list
100 15
        $packedBoxes = new PackedBoxList();
101 15
        $packedBoxes->insertFromArray($boxes);
102
103 15
        return $packedBoxes;
104
    }
105
106
    /**
107
     * Attempt to equalise weight distribution between 2 boxes.
108
     *
109
     * @return bool was the weight rebalanced?
110
     */
111 10
    private function equaliseWeight(PackedBox &$boxA, PackedBox &$boxB, float $targetWeight): bool
112
    {
113 10
        $anyIterationSuccessful = false;
114
115 10
        if ($boxA->getWeight() > $boxB->getWeight()) {
116 10
            $overWeightBox = $boxA;
117 10
            $underWeightBox = $boxB;
118
        } else {
119 1
            $overWeightBox = $boxB;
120 1
            $underWeightBox = $boxA;
121
        }
122
123 10
        $overWeightBoxItems = $overWeightBox->getItems()->asItemArray();
124 10
        $underWeightBoxItems = $underWeightBox->getItems()->asItemArray();
125
126 10
        foreach ($overWeightBoxItems as $key => $overWeightItem) {
127 10
            if (!static::wouldRepackActuallyHelp($overWeightBoxItems, $overWeightItem, $underWeightBoxItems, $targetWeight)) {
128 8
                continue; // moving this item would harm more than help
129
            }
130
131 7
            $newLighterBoxes = $this->doVolumeRepack(array_merge($underWeightBoxItems, [$overWeightItem]), $underWeightBox->getBox());
132 7
            if ($newLighterBoxes->count() !== 1) {
133 2
                continue; // only want to move this item if it still fits in a single box
134
            }
135
136 5
            $underWeightBoxItems[] = $overWeightItem;
137
138 5
            if (count($overWeightBoxItems) === 1) { // sometimes a repack can be efficient enough to eliminate a box
139
                $boxB = $newLighterBoxes->top();
140
                $boxA = null;
141
                $this->boxesQtyAvailable[$underWeightBox->getBox()] = $this->boxesQtyAvailable[$underWeightBox->getBox()] - 1;
142
                $this->boxesQtyAvailable[$overWeightBox->getBox()] = $this->boxesQtyAvailable[$overWeightBox->getBox()] + 1;
143
144
                return true;
145
            }
146
147 5
            unset($overWeightBoxItems[$key]);
148 5
            $newHeavierBoxes = $this->doVolumeRepack($overWeightBoxItems, $overWeightBox->getBox());
149 5
            if (count($newHeavierBoxes) !== 1) {
150
                continue; // this should never happen, if we can pack n+1 into the box, we should be able to pack n
151
            }
152
153 5
            $this->boxesQtyAvailable[$overWeightBox->getBox()] = $this->boxesQtyAvailable[$overWeightBox->getBox()] + 1;
154 5
            $this->boxesQtyAvailable[$underWeightBox->getBox()] = $this->boxesQtyAvailable[$underWeightBox->getBox()] + 1;
155 5
            $this->boxesQtyAvailable[$newHeavierBoxes->top()->getBox()] = $this->boxesQtyAvailable[$newHeavierBoxes->top()->getBox()] - 1;
156 5
            $this->boxesQtyAvailable[$newLighterBoxes->top()->getBox()] = $this->boxesQtyAvailable[$newLighterBoxes->top()->getBox()] - 1;
157 5
            $underWeightBox = $boxB = $newLighterBoxes->top();
158 5
            $overWeightBox = $boxA = $newHeavierBoxes->top();
159
160 5
            $anyIterationSuccessful = true;
161
        }
162
163 10
        return $anyIterationSuccessful;
164
    }
165
166
    /**
167
     * Do a volume repack of a set of items.
168
     */
169 7
    private function doVolumeRepack(iterable $items, Box $currentBox): PackedBoxList
170
    {
171 7
        $packer = new Packer();
172 7
        $packer->setBoxes($this->boxes); // use the full set of boxes to allow smaller/larger for full efficiency
173 7
        foreach ($this->boxes as $box) {
174 7
            $packer->setBoxQuantity($box, $this->boxesQtyAvailable[$box]);
175
        }
176 7
        $packer->setBoxQuantity($currentBox, $this->boxesQtyAvailable[$currentBox] + 1);
177 7
        $packer->setItems($items);
178
179 7
        return $packer->doVolumePacking(true, true);
180
    }
181
182
    /**
183
     * Not every attempted repack is actually helpful - sometimes moving an item between two otherwise identical
184
     * boxes, or sometimes the box used for the now lighter set of items actually weighs more when empty causing
185
     * an increase in total weight.
186
     */
187 10
    private static function wouldRepackActuallyHelp(array $overWeightBoxItems, Item $overWeightItem, array $underWeightBoxItems, float $targetWeight): bool
188
    {
189 10
        $overWeightItemsWeight = array_sum(array_map(static function (Item $item) {return $item->getWeight(); }, $overWeightBoxItems));
190 10
        $underWeightItemsWeight = array_sum(array_map(static function (Item $item) {return $item->getWeight(); }, $underWeightBoxItems));
191
192 10
        if ($overWeightItem->getWeight() + $underWeightItemsWeight > $targetWeight) {
193 8
            return false;
194
        }
195
196 7
        $oldVariance = static::calculateVariance($overWeightItemsWeight, $underWeightItemsWeight);
0 ignored issues
show
Bug introduced by
It seems like $overWeightItemsWeight can also be of type double; however, parameter $boxAWeight of DVDoug\BoxPacker\WeightR...or::calculateVariance() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

196
        $oldVariance = static::calculateVariance(/** @scrutinizer ignore-type */ $overWeightItemsWeight, $underWeightItemsWeight);
Loading history...
Bug introduced by
It seems like $underWeightItemsWeight can also be of type double; however, parameter $boxBWeight of DVDoug\BoxPacker\WeightR...or::calculateVariance() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

196
        $oldVariance = static::calculateVariance($overWeightItemsWeight, /** @scrutinizer ignore-type */ $underWeightItemsWeight);
Loading history...
197 7
        $newVariance = static::calculateVariance($overWeightItemsWeight - $overWeightItem->getWeight(), $underWeightItemsWeight + $overWeightItem->getWeight());
198
199 7
        return $newVariance < $oldVariance;
200
    }
201
202 7
    private static function calculateVariance(int $boxAWeight, int $boxBWeight)
203
    {
204 7
        return ($boxAWeight - (($boxAWeight + $boxBWeight) / 2)) ** 2; // don't need to calculate B and ÷ 2, for a 2-item population the difference from mean is the same for each box
205
    }
206
}
207