Passed
Push — 3.x ( e58d28...ec426a )
by Doug
01:41
created

WeightRedistributor   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 169
Duplicated Lines 0 %

Test Coverage

Coverage 92.41%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 75
c 6
b 1
f 0
dl 0
loc 169
ccs 73
cts 79
cp 0.9241
rs 10
wmc 20

6 Methods

Rating   Name   Duplication   Size   Complexity  
A calculateVariance() 0 3 1
A doVolumeRepack() 0 11 2
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 function max;
18
use const PHP_INT_MAX;
19
use Psr\Log\LoggerAwareInterface;
20
use Psr\Log\LoggerAwareTrait;
21
use Psr\Log\LogLevel;
22
use Psr\Log\NullLogger;
23
use SplObjectStorage;
24
use function usort;
25
26
/**
27
 * Actual packer.
28
 *
29
 * @author Doug Wright
30
 * @internal
31
 */
32
class WeightRedistributor implements LoggerAwareInterface
33
{
34
    use LoggerAwareTrait;
35
36
    /**
37
     * List of box sizes available to pack items into.
38
     *
39
     * @var BoxList
40
     */
41
    private $boxes;
42
43
    /**
44
     * Quantities available of each box type.
45
     *
46
     * @var SplObjectStorage|int[]
47
     */
48
    private $boxesQtyAvailable;
49
50
    /**
51
     * Constructor.
52
     */
53 22
    public function __construct(BoxList $boxList, SplObjectStorage $boxQuantitiesAvailable)
54
    {
55 22
        $this->boxes = $boxList;
56 22
        $this->boxesQtyAvailable = $boxQuantitiesAvailable;
57 22
        $this->logger = new NullLogger();
58 22
    }
59
60
    /**
61
     * Given a solution set of packed boxes, repack them to achieve optimum weight distribution.
62
     */
63 22
    public function redistributeWeight(PackedBoxList $originalBoxes): PackedBoxList
64
    {
65 22
        $targetWeight = $originalBoxes->getMeanItemWeight();
66 22
        $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

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

192
        $oldVariance = static::calculateVariance($overWeightItemsWeight, /** @scrutinizer ignore-type */ $underWeightItemsWeight);
Loading history...
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

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