Test Failed
Push — 2.x-dev ( fa2a34...794087 )
by Doug
01:31
created

WeightRedistributor::doVolumeRepack()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 2
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
8
namespace DVDoug\BoxPacker;
9
10
use Psr\Log\LoggerAwareInterface;
11
use Psr\Log\LoggerAwareTrait;
12
use Psr\Log\LogLevel;
13
use Psr\Log\NullLogger;
14
15
/**
16
 * Actual packer.
17
 *
18
 * @author Doug Wright
19
 * @internal
20
 */
21
class WeightRedistributor implements LoggerAwareInterface
22
{
23
    use LoggerAwareTrait;
24
25
    /**
26
     * List of box sizes available to pack items into.
27
     *
28
     * @var BoxList
29
     */
30
    private $boxes;
31
32
    /**
33
     * Constructor.
34
     *
35
     * @param BoxList $boxList
36
     */
37
    public function __construct(BoxList $boxList)
38
    {
39
        $this->boxes = clone $boxList;
40
        $this->logger = new NullLogger();
41
    }
42
43
    /**
44
     * Given a solution set of packed boxes, repack them to achieve optimum weight distribution.
45
     *
46
     * @param PackedBoxList $originalBoxes
47
     *
48
     * @return PackedBoxList
49
     */
50
    public function redistributeWeight(PackedBoxList $originalBoxes)
51
    {
52
        $targetWeight = $originalBoxes->getMeanWeight();
53
        $this->logger->log(LogLevel::DEBUG, "repacking for weight distribution, weight variance {$originalBoxes->getWeightVariance()}, target weight {$targetWeight}");
54
55
        /** @var PackedBox[] $boxes */
56
        $boxes = iterator_to_array($originalBoxes);
57
58
        usort($boxes, function (PackedBox $boxA, PackedBox $boxB) {
59
            return $boxB->getWeight() - $boxA->getWeight();
60
        });
61
62
        do {
63
            $iterationSuccessful = false;
64
65
            foreach ($boxes as $a => &$boxA) {
66
                foreach ($boxes as $b => &$boxB) {
67
                    if ($b <= $a || $boxA->getWeight() === $boxB->getWeight()) {
68
                        continue; //no need to evaluate
69
                    }
70
71
                    $iterationSuccessful = $this->equaliseWeight($boxA, $boxB, $targetWeight);
72
                    if ($iterationSuccessful) {
73
                        $boxes = array_filter($boxes, function ($box) { //remove any now-empty boxes from the list
74
                            return $box instanceof PackedBox;
75
                        });
76
                        break 2;
77
                    }
78
                }
79
            }
80
        } while ($iterationSuccessful);
81
82
        //Combine back into a single list
83
        $packedBoxes = new PackedBoxList();
84
        $packedBoxes->insertFromArray($boxes);
85
86
        return $packedBoxes;
87
    }
88
89
    /**
90
     * Attempt to equalise weight distribution between 2 boxes.
91
     *
92
     * @param PackedBox $boxA
93
     * @param PackedBox $boxB
94
     * @param float     $targetWeight
95
     *
96
     * @return bool was the weight rebalanced?
97
     */
98
    private function equaliseWeight(PackedBox &$boxA, PackedBox &$boxB, $targetWeight)
99
    {
100
        $anyIterationSuccessful = false;
101
102
        if ($boxA->getWeight() > $boxB->getWeight()) {
103
            $overWeightBox = $boxA;
104
            $underWeightBox = $boxB;
105
        } else {
106
            $overWeightBox = $boxB;
107
            $underWeightBox = $boxA;
108
        }
109
110
        $overWeightBoxItems = $overWeightBox->getItems()->asArray();
111
        $underWeightBoxItems = $underWeightBox->getItems()->asArray();
112
113
        foreach ($overWeightBoxItems as $key => $overWeightItem) {
114
            if ($overWeightItem->getWeight() + $boxB->getWeight() > $targetWeight) {
115
                continue; // moving this item would harm more than help
116
            }
117
118
            $newLighterBoxes = $this->doVolumeRepack(array_merge($underWeightBoxItems, [$overWeightItem]));
119
            if (count($newLighterBoxes) !== 1) {
120
                continue; //only want to move this item if it still fits in a single box
121
            }
122
123
            $underWeightBoxItems[] = $overWeightItem;
124
125
            if (count($overWeightBoxItems) === 1) { //sometimes a repack can be efficient enough to eliminate a box
126
                $boxB = $newLighterBoxes->top();
127
                $boxA = null;
128
129
                return true;
130
            } else {
131
                unset($overWeightBoxItems[$key]);
132
                $newHeavierBoxes = $this->doVolumeRepack($overWeightBoxItems);
133
                if (count($newHeavierBoxes) !== 1) {
134
                    continue;
135
                }
136
137
                if ($this->didRepackActuallyHelp($boxA, $boxB, $newHeavierBoxes->top(), $newLighterBoxes->top())) {
138
                    $boxB = $newLighterBoxes->top();
139
                    $boxA = $newHeavierBoxes->top();
140
                    $anyIterationSuccessful = true;
141
                }
142
            }
143
        }
144
145
        return $anyIterationSuccessful;
146
    }
147
148
    /**
149
     * Do a volume repack of a set of items.
150
     *
151
     * @param array $items
152
     *
153
     * @return PackedBoxList
154
     */
155
    private function doVolumeRepack($items)
156
    {
157
        $packer = new Packer();
158
        $packer->setBoxes($this->boxes); // use the full set of boxes to allow smaller/larger for full efficiency
159
        $packer->setItems($items);
160
161
        return $packer->doVolumePacking();
162
    }
163
164
    /**
165
     * Not every attempted repack is actually helpful - sometimes moving an item between two otherwise identical
166
     * boxes, or sometimes the box used for the now lighter set of items actually weighs more when empty causing
167
     * an increase in total weight.
168
     *
169
     * @param PackedBox $oldBoxA
170
     * @param PackedBox $oldBoxB
171
     * @param PackedBox $newBoxA
172
     * @param PackedBox $newBoxB
173
     *
174
     * @return bool
175
     */
176
    private function didRepackActuallyHelp(PackedBox $oldBoxA, PackedBox $oldBoxB, PackedBox $newBoxA, PackedBox $newBoxB)
177
    {
178
        $oldList = new PackedBoxList();
179
        $oldList->insertFromArray([$oldBoxA, $oldBoxB]);
180
181
        $newList = new PackedBoxList();
182
        $newList->insertFromArray([$newBoxA, $newBoxB]);
183
184
        return $newList->getWeightVariance() < $oldList->getWeightVariance();
185
    }
186
}
187