Passed
Push — 3.x ( ef7dd6...5c24fe )
by Doug
01:52
created

WeightRedistributor   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 169
Duplicated Lines 0 %

Test Coverage

Coverage 92%

Importance

Changes 8
Bugs 1 Features 0
Metric Value
eloc 75
c 8
b 1
f 0
dl 0
loc 169
ccs 69
cts 75
cp 0.92
rs 10
wmc 20

6 Methods

Rating   Name   Duplication   Size   Complexity  
A doVolumeRepack() 0 11 2
A calculateVariance() 0 3 1
A __construct() 0 5 1
B equaliseWeight() 0 53 7
A wouldRepackActuallyHelp() 0 13 2
B redistributeWeight() 0 37 7
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
     * Constructor.
50
     */
51 13
    public function __construct(BoxList $boxList, SplObjectStorage $boxQuantitiesAvailable)
52
    {
53 13
        $this->boxes = $boxList;
54 13
        $this->boxesQtyAvailable = $boxQuantitiesAvailable;
55 13
        $this->logger = new NullLogger();
56 13
    }
57
58
    /**
59
     * Given a solution set of packed boxes, repack them to achieve optimum weight distribution.
60
     */
61 13
    public function redistributeWeight(PackedBoxList $originalBoxes): PackedBoxList
62
    {
63 13
        $targetWeight = $originalBoxes->getMeanItemWeight();
64 13
        $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

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

190
        $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

190
        $oldVariance = static::calculateVariance($overWeightItemsWeight, /** @scrutinizer ignore-type */ $underWeightItemsWeight);
Loading history...
191 7
        $newVariance = static::calculateVariance($overWeightItemsWeight - $overWeightItem->getWeight(), $underWeightItemsWeight + $overWeightItem->getWeight());
192
193 7
        return $newVariance < $oldVariance;
194
    }
195
196 7
    private static function calculateVariance(int $boxAWeight, int $boxBWeight)
197
    {
198 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
199
    }
200
}
201