easy-box-packer 0.0.7 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +5 -5
- data/README.md +173 -8
- data/easy-box-packer.rb +615 -114
- metadata +13 -32
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
|
-
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: da57ae690efc3b892a4a933e0998323821a886b6a1504ecb21db3d36843d2823
|
|
4
|
+
data.tar.gz: 6a3b4a7793dc18ea0d29eeb54619f9c68849e528da56ab8cbc0d2db9c86340fb
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 70c24cc1541b819ea76fe4bd3a609114090b77e52b94fa893f77634d6275ec93948736da7aeef386765e2b509a4906904cafdea392990af20d127bbbbbcee2c8
|
|
7
|
+
data.tar.gz: ae3f7c31ebd1afae72cc463041c34cb84cc95d600358abed76f7d42ae16e4705c9bf11acff8746fb0f90bc3780883bafa1cad3a41ffcb5d4732e1cdec0394021
|
data/README.md
CHANGED
|
@@ -30,27 +30,192 @@ cont = EasyBoxPacker.pack(
|
|
|
30
30
|
)
|
|
31
31
|
|
|
32
32
|
cont[:packings].length # 3
|
|
33
|
-
cont[:packings][0][:weight] # 47
|
|
33
|
+
cont[:packings][0][:weight] # 47.0
|
|
34
34
|
cont[:packings][0][:placements].length # 1
|
|
35
35
|
cont[:packings][0][:placements][0][:dimensions] # [2, 3, 5]
|
|
36
36
|
cont[:packings][0][:placements][0][:position] # [0, 0, 0]
|
|
37
|
-
cont[:packings][1][:weight] # 47
|
|
37
|
+
cont[:packings][1][:weight] # 47.0
|
|
38
38
|
cont[:packings][1][:placements].length # 1
|
|
39
39
|
cont[:packings][1][:placements][0][:dimensions] # [2, 3, 5]
|
|
40
40
|
cont[:packings][1][:placements][0][:position] # [0, 0, 0]
|
|
41
|
-
cont[:packings][2][:weight] # 31
|
|
41
|
+
cont[:packings][2][:weight] # 31.0
|
|
42
42
|
cont[:packings][2][:placements].length # 2
|
|
43
|
-
cont[:packings][2][:placements][0][:dimensions] # [1,
|
|
43
|
+
cont[:packings][2][:placements][0][:dimensions] # [1, 1, 4]
|
|
44
44
|
cont[:packings][2][:placements][0][:position] # [0, 0, 0]
|
|
45
|
-
cont[:packings][2][:placements][1][:dimensions] # [
|
|
46
|
-
cont[:packings][2][:placements][1][:position] # [
|
|
45
|
+
cont[:packings][2][:placements][1][:dimensions] # [1, 3, 3]
|
|
46
|
+
cont[:packings][2][:placements][1][:position] # [0, 1, 0]
|
|
47
|
+
cont[:errors] # []
|
|
47
48
|
```
|
|
48
49
|
|
|
50
|
+
Notes:
|
|
51
|
+
|
|
52
|
+
- `weight_limit` and `weight` are optional; without `weight_limit` there is no weight restriction.
|
|
53
|
+
- Positions and dimensions of placements are in the container's frame with its
|
|
54
|
+
dimensions sorted descending (e.g. `[20, 15, 13]` for the container above).
|
|
55
|
+
- Items that are too heavy, too big or have invalid dimensions (not three positive numbers)
|
|
56
|
+
are reported in `errors` instead of being placed. An invalid container raises `ArgumentError`.
|
|
57
|
+
|
|
49
58
|
### Get a reasonable smallest container by given boxes
|
|
50
59
|
|
|
51
|
-
```
|
|
60
|
+
```ruby
|
|
52
61
|
container = EasyBoxPacker.find_smallest_container(
|
|
53
62
|
items: Array.new(1000) {{ dimensions: [1, 1, 1] }}
|
|
54
63
|
)
|
|
55
|
-
container # [10, 10, 10]
|
|
64
|
+
container # [10.0, 10.0, 10.0]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
All sizes are in **cm**. The result is always floats sorted ascending, or `nil`
|
|
68
|
+
when no container satisfies the limits below. It is a heuristic: a small
|
|
69
|
+
container, not a proven minimum.
|
|
70
|
+
|
|
71
|
+
It works in two steps:
|
|
72
|
+
|
|
73
|
+
1. A quick heuristic that grows a container item by item.
|
|
74
|
+
2. A refining search over side lengths built from sums of item sides, which keeps
|
|
75
|
+
the best container found until `time_limit` runs out. It is never worse than step 1.
|
|
76
|
+
|
|
77
|
+
```ruby
|
|
78
|
+
EasyBoxPacker.find_smallest_container(
|
|
79
|
+
items: items,
|
|
80
|
+
time_limit: 0.5, # seconds (default 0.5). nil = no limit, 0 = step 1 only
|
|
81
|
+
max_attempts: nil, # max candidates test-packed; same result on every machine
|
|
82
|
+
max_length: 120, # longest side allowed (cm), e.g. your carrier's limit
|
|
83
|
+
max_length_plus_girth: 300, # length + 2 * (width + height) allowed (cm)
|
|
84
|
+
cost: nil # custom cost, see below
|
|
85
|
+
)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`time_limit` is a soft limit for the whole call: step 1 always finishes, and
|
|
89
|
+
the test pack already running when the time runs out also finishes.
|
|
90
|
+
|
|
91
|
+
By default the cheapest container is the one with the smallest volume, then the
|
|
92
|
+
smallest length + girth. Carriers charge on dimensional weight (volume) plus
|
|
93
|
+
surcharges for long parcels, so pass your own `cost` to model your carrier.
|
|
94
|
+
It receives `[a, b, c]` in cm (sorted ascending), returns anything comparable
|
|
95
|
+
(lower is better), and must not decrease when a side grows:
|
|
96
|
+
|
|
97
|
+
```ruby
|
|
98
|
+
# dimensional weight (divisor 5000) + a surcharge when the longest side is over 60 cm
|
|
99
|
+
cost = ->(d) { (d.inject(:*) / 5000.0).ceil + (d.max > 60 ? 20 : 0) }
|
|
100
|
+
EasyBoxPacker.find_smallest_container(items: items, cost: cost)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Choose boxes from the boxes you have
|
|
104
|
+
|
|
105
|
+
```ruby
|
|
106
|
+
result = EasyBoxPacker.select_box(
|
|
107
|
+
boxes: [
|
|
108
|
+
{ id: 'S', dimensions: [20, 15, 10], weight_limit: 5, cost: 10 }, # inside size in cm, kg
|
|
109
|
+
{ id: 'M', dimensions: [30, 25, 20], weight_limit: 10, cost: 18 },
|
|
110
|
+
{ id: 'L', dimensions: [45, 35, 30], weight_limit: 20, cost: 30 }
|
|
111
|
+
],
|
|
112
|
+
items: [
|
|
113
|
+
{ id: 'mug', dimensions: [12, 9, 9], weight: 0.4 },
|
|
114
|
+
{ id: 'book', dimensions: [24, 17, 3], weight: 0.6 }
|
|
115
|
+
]
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
result[:boxes].first[:box][:id] # "M"
|
|
119
|
+
result[:boxes].first[:placements].map { |p| p[:item][:id] } # ["book", "mug"]
|
|
120
|
+
result[:boxes].first[:placements].first[:position] # where to put it
|
|
121
|
+
result[:total_cost] # 18
|
|
122
|
+
result[:unpacked] # [] or [{ item:, reason: :too_big }]
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
It returns the cheapest single box that holds everything; when none does, it
|
|
126
|
+
fills the box that packs the most item volume per cost and repeats.
|
|
127
|
+
|
|
128
|
+
| option | default | meaning |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `allow_multiple_boxes` | `true` | split items over several boxes when no single box fits |
|
|
131
|
+
| `padding` | `0` | cm of cushioning kept free on every side (a box's own `:padding` wins) |
|
|
132
|
+
| `cost` | `box[:cost]` or volume | lambda `box -> number`, lower is better |
|
|
133
|
+
| `max_items` | `nil` | raise `ArgumentError` when more items are given |
|
|
134
|
+
| `time_limit` | `nil` | soft limit in seconds; after it only the fastest strategy is used |
|
|
135
|
+
| `split_strategies`, `greedy_fallback` | | passed to `pack` |
|
|
136
|
+
|
|
137
|
+
`unpacked` reasons: `:invalid_dimensions`, `:too_big`, `:too_heavy`, `:no_single_box`.
|
|
138
|
+
|
|
139
|
+
Each box in the result also has `container_dimensions` (the frame the positions are in,
|
|
140
|
+
the third axis is up) and every placement has `step:` and `support:`, see below.
|
|
141
|
+
|
|
142
|
+
### Upright and fragile items
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
{ dimensions: [8, 8, 25], upright: true } # dimensions[2] is the height and stays vertical
|
|
146
|
+
{ dimensions: [20, 15, 6], fragile: true } # nothing is placed on top of it
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
The box may be stood on another side to fit upright items; the frame used is returned
|
|
150
|
+
as `container_dimensions` (`pack`) and the third axis is up. With constraints the flat
|
|
151
|
+
stacking fallback is not used.
|
|
152
|
+
|
|
153
|
+
### Loading order
|
|
154
|
+
|
|
155
|
+
`EasyBoxPacker.loading_order(placements)` sorts placements bottom layer first, then
|
|
156
|
+
from the back corner, and adds `step:` (1, 2, ...) and `support:`, the share of the
|
|
157
|
+
item's bottom resting on the floor or on items below. `support` below 1.0 means the
|
|
158
|
+
item overhangs empty space, fill it with cushioning or warn the packer.
|
|
159
|
+
`select_box` already adds both keys to its placements.
|
|
160
|
+
|
|
161
|
+
### Tuning options
|
|
162
|
+
|
|
163
|
+
| option | methods | default | meaning |
|
|
164
|
+
|---|---|---|---|
|
|
165
|
+
| `split_strategies` | all | `EasyBoxPacker::SPLIT_STRATEGIES` | free space split strategies tried in order (`:legacy`, `:max_space`, `0`..`5`). `[:legacy]` is fastest |
|
|
166
|
+
| `greedy_fallback` | all | `true` | return all items stacked flat when that fits but packing needs more containers |
|
|
167
|
+
| `beam_width` | `find_smallest_container` | `1` | candidates kept per step of the heuristic search |
|
|
168
|
+
| `max_side_values` | `find_smallest_container` | `1000` | max distinct side lengths tried per axis while refining |
|
|
169
|
+
|
|
170
|
+
Every placement includes `item:`, the item hash you passed in, so you can tell
|
|
171
|
+
which item goes where.
|
|
172
|
+
|
|
173
|
+
### Using it from a web API
|
|
174
|
+
|
|
175
|
+
- All state is passed in, nothing global is changed, so it is safe to call from
|
|
176
|
+
several threads.
|
|
177
|
+
- Keys must be symbols: parse JSON with `JSON.parse(body, symbolize_names: true)`.
|
|
178
|
+
- It is CPU bound. Set `max_items` and `time_limit`, and run it outside the request
|
|
179
|
+
thread (a job queue) or with a request timeout.
|
|
180
|
+
|
|
181
|
+
## Development
|
|
182
|
+
|
|
183
|
+
```
|
|
184
|
+
bundle install
|
|
185
|
+
bundle exec rspec easy-box-packer_spec.rb
|
|
56
186
|
```
|
|
187
|
+
|
|
188
|
+
## Changelog
|
|
189
|
+
|
|
190
|
+
### 0.4.0
|
|
191
|
+
|
|
192
|
+
- Item constraints: `upright: true` and `fragile: true`.
|
|
193
|
+
- `loading_order` with `step:` and `support:`; `select_box` placements include them.
|
|
194
|
+
- `pack` and `select_box` results include `container_dimensions`.
|
|
195
|
+
|
|
196
|
+
### 0.3.0
|
|
197
|
+
|
|
198
|
+
- New `select_box`: choose boxes from your own box list (cost, weight limit, padding,
|
|
199
|
+
several boxes when needed) and get the placements.
|
|
200
|
+
- Placements include the original `item:`.
|
|
201
|
+
- `split_strategies`, `greedy_fallback`, `beam_width` and `max_side_values` can be passed in.
|
|
202
|
+
|
|
203
|
+
### 0.2.0
|
|
204
|
+
|
|
205
|
+
- `find_smallest_container` refines its first answer with a search over side lengths,
|
|
206
|
+
e.g. case 7 goes from 30 x 30 x 220 to 30 x 55 x 110 (smaller and much shorter).
|
|
207
|
+
- New options: `time_limit`, `max_attempts`, `max_length`, `max_length_plus_girth`, `cost`.
|
|
208
|
+
- Sizes are documented as cm.
|
|
209
|
+
|
|
210
|
+
### 0.1.0
|
|
211
|
+
|
|
212
|
+
- Fix: the stacking fallback returned overlapping / out-of-bounds placements.
|
|
213
|
+
- Fix: a missing `weight_limit` rejected every item that had a weight.
|
|
214
|
+
- Fix: the stacked ("greedy") container height was rounded down (e.g. 1.04 -> 1.0), producing a container that is too small.
|
|
215
|
+
- Fix: `find_smallest_container` crashed on empty items or when no candidate fit.
|
|
216
|
+
- Fix: invalid dimensions (zero, negative, non numeric) were silently "placed".
|
|
217
|
+
- Fix: float tolerance when comparing sizes.
|
|
218
|
+
- Improve: try more ways of splitting free space, so fewer containers are needed and
|
|
219
|
+
`find_smallest_container` finds smaller containers.
|
|
220
|
+
- Change: `find_smallest_container` always returns floats sorted ascending.
|
|
221
|
+
- Require Ruby >= 2.7, rspec ~> 3.13, drop pry.
|
data/easy-box-packer.rb
CHANGED
|
@@ -1,37 +1,474 @@
|
|
|
1
1
|
module EasyBoxPacker
|
|
2
|
+
# Tolerance for floating point comparisons (e.g. 0.1 + 0.2 vs 0.3).
|
|
3
|
+
EPSILON = 1e-9
|
|
4
|
+
|
|
5
|
+
# Ways of choosing how the free space around a placement is split.
|
|
6
|
+
# :legacy is the original heuristic and is always tried first so results
|
|
7
|
+
# that already fit in one container are unchanged; the others are only
|
|
8
|
+
# tried when :legacy needs more than one container.
|
|
9
|
+
SPLIT_STRATEGIES = [:legacy, :max_space, 0, 1, 2, 3, 4, 5].freeze
|
|
10
|
+
|
|
11
|
+
# Number of candidates kept at each step of the smallest container search.
|
|
12
|
+
# 1 reproduces the original search (follow the most cube-like candidate).
|
|
13
|
+
SEARCH_BEAM_WIDTH = 1
|
|
14
|
+
|
|
15
|
+
# Default seconds find_smallest_container spends refining its first answer.
|
|
16
|
+
DEFAULT_TIME_LIMIT = 0.5
|
|
17
|
+
|
|
18
|
+
# Max distinct side lengths tried per axis while refining.
|
|
19
|
+
MAX_SIDE_VALUES = 1000
|
|
20
|
+
|
|
21
|
+
UNPACKED_MESSAGES = {
|
|
22
|
+
invalid_dimensions: 'has invalid dimensions',
|
|
23
|
+
too_big: 'is too big for every box',
|
|
24
|
+
too_heavy: 'is too heavy for every box',
|
|
25
|
+
no_single_box: 'does not fit in a single box with the other items'
|
|
26
|
+
}.freeze
|
|
27
|
+
|
|
2
28
|
class << self
|
|
3
|
-
|
|
29
|
+
# Pack items into as few copies of `container` as possible.
|
|
30
|
+
#
|
|
31
|
+
# All placements are expressed in the container's frame with its
|
|
32
|
+
# dimensions sorted descending (length >= width >= height). Each placement
|
|
33
|
+
# has `item:`, the item hash that was given, so callers can tell which item goes where.
|
|
34
|
+
#
|
|
35
|
+
# split_strategies - free space split strategies to try, in order, until one needs a single
|
|
36
|
+
# container. Any of :legacy, :max_space, 0..5. Default: SPLIT_STRATEGIES.
|
|
37
|
+
# [:legacy] is the fastest and reproduces 0.0.x results.
|
|
38
|
+
# greedy_fallback - when more than one container is needed but all items stacked flat
|
|
39
|
+
# would fit, return that stack instead (default true).
|
|
40
|
+
#
|
|
41
|
+
# Item constraints (optional):
|
|
42
|
+
# upright: true - dimensions[2] is the item's height and must stay vertical
|
|
43
|
+
# (it can still turn around the vertical axis).
|
|
44
|
+
# fragile: true - nothing may be placed on top of it.
|
|
45
|
+
# The vertical axis is the third axis of the result. Without constraints the frame is
|
|
46
|
+
# the container sorted descending; with them the container may be stood on another
|
|
47
|
+
# side, the frame used is returned as :container_dimensions.
|
|
48
|
+
def pack(container:, items:, split_strategies: SPLIT_STRATEGIES, greedy_fallback: true)
|
|
49
|
+
validate_container!(container)
|
|
50
|
+
validate_split_strategies!(split_strategies)
|
|
51
|
+
weight_limit = weight_limit_of(container)
|
|
52
|
+
constrained = constrained?(items)
|
|
53
|
+
frames = constrained ? container_frames(container[:dimensions]) : [container[:dimensions].sort.reverse]
|
|
54
|
+
|
|
55
|
+
best = nil
|
|
56
|
+
frames.each do |frame|
|
|
57
|
+
split_strategies.each do |strategy|
|
|
58
|
+
result = pack_with_strategy(frame, items, weight_limit, strategy)
|
|
59
|
+
if best.nil? || ([result[:errors].size, result[:packings].size] <=> [best[:errors].size, best[:packings].size]) < 0
|
|
60
|
+
best = result
|
|
61
|
+
end
|
|
62
|
+
break if best[:packings].size <= 1
|
|
63
|
+
end
|
|
64
|
+
break if best[:packings].size <= 1 && best[:errors].empty?
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# the flat stack ignores constraints, so it is only used without them
|
|
68
|
+
if greedy_fallback && !constrained && best[:packings].size > 1 && check_container_is_bigger_than_greedy_box(container, items)
|
|
69
|
+
{ packings: generate_packing_for_greedy_box(container, items), errors: [],
|
|
70
|
+
container_dimensions: container[:dimensions].sort.reverse }
|
|
71
|
+
else
|
|
72
|
+
best
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Placements in the order to put them in the box: bottom layer first, then from
|
|
77
|
+
# the back corner. Each gets step: (1, 2, ...) and support: the share of its
|
|
78
|
+
# bottom resting on the box floor or on items below (1.0 = fully supported).
|
|
79
|
+
def loading_order(placements)
|
|
80
|
+
with_steps(placements).sort_by { |pl| pl[:step] }
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Choose boxes from the boxes you have and show how to pack the items in them.
|
|
84
|
+
#
|
|
85
|
+
# boxes - [{ dimensions: [l, w, h] (cm, inside), weight_limit: kg (optional),
|
|
86
|
+
# cost: number (optional, default volume), padding: cm (optional),
|
|
87
|
+
# any other keys such as id: are returned untouched }]
|
|
88
|
+
# items - [{ dimensions: [l, w, h] (cm), weight: kg (optional), id: ... }]
|
|
89
|
+
# allow_multiple_boxes - split the items over several boxes when no single box fits (default true).
|
|
90
|
+
# padding - cushioning in cm kept free on every side of every box (default 0).
|
|
91
|
+
# A box's own :padding overrides it.
|
|
92
|
+
# cost - lambda taking a box hash and returning a number, lower is better.
|
|
93
|
+
# Default: box[:cost], or the box volume when it has none.
|
|
94
|
+
# max_items - raise ArgumentError when more items are given (default nil, no limit).
|
|
95
|
+
# time_limit - soft limit in seconds (default nil). After it only the first split
|
|
96
|
+
# strategy is used: still valid, maybe one more box than needed.
|
|
97
|
+
# split_strategies,
|
|
98
|
+
# greedy_fallback - passed to #pack.
|
|
99
|
+
#
|
|
100
|
+
# Returns { boxes: [{ box:, placements:, weight:, cost: }], total_cost:,
|
|
101
|
+
# unpacked: [{ item:, reason: }], errors: [String] }.
|
|
102
|
+
# reason is one of :invalid_dimensions, :too_big, :too_heavy, :no_single_box.
|
|
103
|
+
# Placements are in the box's usable space (inside dimensions minus padding), sorted descending.
|
|
104
|
+
def select_box(boxes:, items:, allow_multiple_boxes: true, padding: 0, cost: nil, max_items: nil,
|
|
105
|
+
time_limit: nil, split_strategies: SPLIT_STRATEGIES, greedy_fallback: true)
|
|
106
|
+
raise ArgumentError, 'boxes must not be empty' if boxes.nil? || boxes.empty?
|
|
107
|
+
raise ArgumentError, 'items must be an array' unless items.is_a?(Array)
|
|
108
|
+
validate_non_negative!(:padding, padding)
|
|
109
|
+
validate_non_negative!(:time_limit, time_limit)
|
|
110
|
+
validate_non_negative!(:max_items, max_items)
|
|
111
|
+
raise ArgumentError, "too many items: #{items.size} (max_items: #{max_items})" if max_items && items.size > max_items
|
|
112
|
+
raise ArgumentError, 'cost must respond to #call' if cost && !cost.respond_to?(:call)
|
|
113
|
+
validate_split_strategies!(split_strategies)
|
|
114
|
+
pack_options = { split_strategies: split_strategies, greedy_fallback: greedy_fallback }
|
|
115
|
+
|
|
116
|
+
candidates = boxes.map do |box|
|
|
117
|
+
raise ArgumentError, "invalid box dimensions: #{box.inspect}" unless box.is_a?(Hash) && valid_dimensions?(box[:dimensions])
|
|
118
|
+
box_padding = box.key?(:padding) ? box[:padding] : padding
|
|
119
|
+
validate_non_negative!(:padding, box_padding)
|
|
120
|
+
usable = box[:dimensions].map { |d| d - 2 * box_padding }
|
|
121
|
+
next unless usable.all? { |d| d > EPSILON }
|
|
122
|
+
box_cost = cost ? cost.call(box) : (box[:cost] || volume(box[:dimensions]))
|
|
123
|
+
raise ArgumentError, "box cost must be a non-negative number: #{box.inspect}" unless box_cost.is_a?(Numeric) && box_cost >= 0
|
|
124
|
+
{ box: box, container: { dimensions: usable, weight_limit: box[:weight_limit] }, cost: box_cost }
|
|
125
|
+
end.compact
|
|
126
|
+
|
|
127
|
+
unpacked = []
|
|
128
|
+
remaining = []
|
|
129
|
+
items.each do |item|
|
|
130
|
+
if !item.is_a?(Hash) || !valid_dimensions?(item[:dimensions])
|
|
131
|
+
unpacked << { item: item, reason: :invalid_dimensions }
|
|
132
|
+
elsif candidates.none? { |c| fits_in_one?(c[:container][:dimensions], [item], pack_options.merge(weight_limit: c[:container][:weight_limit])) }
|
|
133
|
+
fits_by_size = candidates.any? { |c| fits_in_one?(c[:container][:dimensions], [item], pack_options) }
|
|
134
|
+
unpacked << { item: item, reason: fits_by_size ? :too_heavy : :too_big }
|
|
135
|
+
else
|
|
136
|
+
remaining << item
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
deadline = time_limit && Process.clock_gettime(Process::CLOCK_MONOTONIC) + time_limit
|
|
141
|
+
chosen = []
|
|
142
|
+
until remaining.empty?
|
|
143
|
+
remaining_volume = remaining.sum { |i| volume(i[:dimensions]) }
|
|
144
|
+
remaining_weight = remaining.sum { |i| i[:weight].to_f }
|
|
145
|
+
|
|
146
|
+
results = candidates.map do |cand|
|
|
147
|
+
# a box too small or too weak for everything can not be the single box,
|
|
148
|
+
# so only the fastest strategy is needed to rank it for filling
|
|
149
|
+
could_hold_all = volume(cand[:container][:dimensions]) + EPSILON >= remaining_volume &&
|
|
150
|
+
weight_limit_of(cand[:container]) + EPSILON >= remaining_weight
|
|
151
|
+
out_of_time = deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
|
|
152
|
+
options = could_hold_all && !out_of_time ? pack_options : pack_options.merge(split_strategies: [split_strategies.first])
|
|
153
|
+
[cand, pack(container: cand[:container], items: remaining, **options)]
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# cheapest single box that holds everything left
|
|
157
|
+
single = results
|
|
158
|
+
.select { |_, r| r[:packings].size == 1 && r[:errors].empty? }
|
|
159
|
+
.min_by { |c, _| [c[:cost], volume(c[:container][:dimensions])] }
|
|
160
|
+
if single
|
|
161
|
+
chosen << box_result(single[0], single[1])
|
|
162
|
+
break
|
|
163
|
+
end
|
|
164
|
+
unless allow_multiple_boxes
|
|
165
|
+
remaining.each { |item| unpacked << { item: item, reason: :no_single_box } }
|
|
166
|
+
break
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# otherwise fill the box that packs the most item volume per cost, then repeat
|
|
170
|
+
c, packing, r = results.map do |cand, res|
|
|
171
|
+
[cand, res[:packings].max_by { |p| packed_volume(p) }, res]
|
|
172
|
+
end.reject { |_, p, _| p.nil? }.max_by do |cand, p, _|
|
|
173
|
+
[cand[:cost].zero? ? Float::INFINITY : packed_volume(p) / cand[:cost], packed_volume(p), -cand[:cost]]
|
|
174
|
+
end
|
|
175
|
+
chosen << box_result(c, r.merge(packings: [packing]))
|
|
176
|
+
packed = packing[:placements].map { |pl| pl[:item] }
|
|
177
|
+
remaining = remaining.reject { |item| packed.any? { |p| p.equal?(item) } }
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
{
|
|
181
|
+
boxes: chosen,
|
|
182
|
+
total_cost: chosen.sum { |b| b[:cost] },
|
|
183
|
+
unpacked: unpacked,
|
|
184
|
+
errors: unpacked.map { |u| "Item: #{u[:item]} #{UNPACKED_MESSAGES[u[:reason]]}" }
|
|
185
|
+
}
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# Find a small container (dimensions in cm, floats sorted ascending) that holds all items.
|
|
189
|
+
#
|
|
190
|
+
# time_limit - soft limit in seconds for the whole call (default 0.5): no new
|
|
191
|
+
# candidate is tried after it, the first heuristic answer is always
|
|
192
|
+
# computed. nil = no time limit, 0 = skip refining (0.1.0 behaviour).
|
|
193
|
+
# max_attempts - max number of candidate containers test-packed while refining.
|
|
194
|
+
# Unlike time_limit it gives the same result on every machine. nil = no limit.
|
|
195
|
+
# max_length - longest side allowed (cm), e.g. a carrier limit.
|
|
196
|
+
# max_length_plus_girth - max length + 2 * (width + height) allowed (cm).
|
|
197
|
+
# cost - lambda taking [a, b, c] (sorted ascending, cm) and returning a Comparable,
|
|
198
|
+
# lower is better. It must not decrease when a side grows.
|
|
199
|
+
# Default: [volume, length + girth].
|
|
200
|
+
#
|
|
201
|
+
# beam_width - candidates kept per step of the heuristic search (default 1).
|
|
202
|
+
# max_side_values - max distinct side lengths tried per axis while refining (default 1000).
|
|
203
|
+
# split_strategies,
|
|
204
|
+
# greedy_fallback - passed to #pack.
|
|
205
|
+
#
|
|
206
|
+
# Returns nil when no container satisfies max_length / max_length_plus_girth.
|
|
207
|
+
def find_smallest_container(items:, time_limit: DEFAULT_TIME_LIMIT, max_attempts: nil,
|
|
208
|
+
max_length: nil, max_length_plus_girth: nil, cost: nil,
|
|
209
|
+
beam_width: SEARCH_BEAM_WIDTH, max_side_values: MAX_SIDE_VALUES,
|
|
210
|
+
split_strategies: SPLIT_STRATEGIES, greedy_fallback: true)
|
|
211
|
+
raise ArgumentError, 'items must not be empty' if items.nil? || items.empty?
|
|
212
|
+
items.each do |item|
|
|
213
|
+
raise ArgumentError, "invalid dimensions for item: #{item}" unless valid_dimensions?(item[:dimensions])
|
|
214
|
+
end
|
|
215
|
+
validate_non_negative!(:time_limit, time_limit)
|
|
216
|
+
validate_non_negative!(:max_attempts, max_attempts)
|
|
217
|
+
validate_non_negative!(:max_length, max_length)
|
|
218
|
+
validate_non_negative!(:max_length_plus_girth, max_length_plus_girth)
|
|
219
|
+
raise ArgumentError, 'cost must respond to #call' if cost && !cost.respond_to?(:call)
|
|
220
|
+
raise ArgumentError, 'beam_width must be a positive integer' unless beam_width.is_a?(Integer) && beam_width > 0
|
|
221
|
+
raise ArgumentError, 'max_side_values must be a positive integer' unless max_side_values.is_a?(Integer) && max_side_values > 0
|
|
222
|
+
validate_split_strategies!(split_strategies)
|
|
223
|
+
pack_options = { split_strategies: split_strategies, greedy_fallback: greedy_fallback }
|
|
224
|
+
|
|
225
|
+
started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
226
|
+
limits = { max_length: max_length, max_length_plus_girth: max_length_plus_girth }
|
|
227
|
+
start = heuristic_smallest_container(items, beam_width, pack_options)
|
|
228
|
+
start = nil unless within_limits?(start, limits)
|
|
229
|
+
return start && normalize(start) if items.size == 1
|
|
230
|
+
|
|
231
|
+
best = refine_container(
|
|
232
|
+
items, start,
|
|
233
|
+
deadline: time_limit && started_at + time_limit, max_attempts: max_attempts, limits: limits, cost: cost,
|
|
234
|
+
max_side_values: max_side_values, pack_options: pack_options
|
|
235
|
+
)
|
|
236
|
+
best && normalize(best)
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
private
|
|
240
|
+
|
|
241
|
+
# Original search: grow a container item by item, then compare with the greedy box.
|
|
242
|
+
def heuristic_smallest_container(items, beam_width, pack_options)
|
|
243
|
+
# order items from biggest to smallest
|
|
244
|
+
sorted_items = items.sort_by { |h| h[:dimensions].sort }.reverse
|
|
245
|
+
return sorted_items.first[:dimensions] if sorted_items.size == 1
|
|
246
|
+
|
|
247
|
+
min_vol = items.map { |h| h[:dimensions].inject(:*) }.inject(:+)
|
|
248
|
+
possible_containers = find_possible_containers(
|
|
249
|
+
container: sorted_items.first[:dimensions],
|
|
250
|
+
items: sorted_items.map { |i| i[:dimensions] },
|
|
251
|
+
min_vol: min_vol,
|
|
252
|
+
beam_width: beam_width
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
select_container = possible_containers
|
|
256
|
+
.sort_by { |a| [volume(a), a.inject(:+)] }
|
|
257
|
+
.find { |c| fits_in_one?(c, items, pack_options) }
|
|
258
|
+
|
|
259
|
+
if constrained?(items)
|
|
260
|
+
# the flat stack breaks upright / fragile items: fall back to the items in one row
|
|
261
|
+
return select_container if select_container
|
|
262
|
+
row = row_box(items)
|
|
263
|
+
return fits_in_one?(row, items, pack_options) ? row : nil
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# The greedy box (all items laid flat and stacked) always fits.
|
|
267
|
+
greedy_box = item_greedy_box(items)
|
|
268
|
+
prefer_greedy_box?(greedy_box, select_container) ? greedy_box : select_container
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
# All items side by side in one layer (nothing on top of anything), upright ones standing.
|
|
272
|
+
def row_box(items)
|
|
273
|
+
sides = items.map do |i|
|
|
274
|
+
d = i[:dimensions]
|
|
275
|
+
if i[:upright]
|
|
276
|
+
w, l = d[0..1].sort
|
|
277
|
+
[w, l, d[2]]
|
|
278
|
+
else
|
|
279
|
+
d.sort
|
|
280
|
+
end
|
|
281
|
+
end
|
|
282
|
+
[sides.sum { |s| s[0] }.round(6), sides.map { |s| s[1] }.max, sides.map { |s| s[2] }.max]
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
# Every container side is (at most) a sum of item sides, so enumerate sides
|
|
286
|
+
# (a <= b <= c) from those sums and test-pack candidates that would be cheaper
|
|
287
|
+
# than the best one found so far. Starts from `best` so it is never worse.
|
|
288
|
+
def refine_container(items, best, deadline:, max_attempts:, limits:, cost:, max_side_values:, pack_options:)
|
|
289
|
+
return best if max_attempts == 0
|
|
290
|
+
return best if deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
|
|
291
|
+
cost_of = cost || method(:default_cost)
|
|
292
|
+
|
|
293
|
+
sorted = items.map { |i| i[:dimensions].sort }
|
|
294
|
+
min_a, min_b, min_c = (0..2).map { |k| sorted.map { |d| d[k] }.max }
|
|
295
|
+
min_vol = sorted.sum { |d| volume(d) }
|
|
296
|
+
|
|
297
|
+
best = best && best.map(&:to_f).sort
|
|
298
|
+
best_cost = best && cost_of.call(best)
|
|
299
|
+
beats_best = ->(dims) { best.nil? || (cost_of.call(dims) <=> best_cost) < 0 }
|
|
300
|
+
|
|
301
|
+
# longest side worth trying: stacking every item end to end always fits,
|
|
302
|
+
# and a longer side can not beat the best cost found so far
|
|
303
|
+
cap = sorted.sum { |d| d[2] }
|
|
304
|
+
cap = [cap, limits[:max_length]].min if limits[:max_length]
|
|
305
|
+
cap = largest_side_beating(cap, min_a, min_b, min_c, beats_best) if best
|
|
306
|
+
values = side_values(sorted, cap, max_side_values)
|
|
307
|
+
attempts = 0
|
|
308
|
+
|
|
309
|
+
# Try the smallest side closest to a cube first, so that when the time limit
|
|
310
|
+
# stops the search early the answer is compact rather than long and thin.
|
|
311
|
+
cube_side = Math.cbrt(min_vol)
|
|
312
|
+
a_values = values.select { |a| a >= min_a - EPSILON }.sort_by { |a| [(a - cube_side).abs, a] }
|
|
313
|
+
|
|
314
|
+
# cost never decreases when a side grows, so cost(a, b, c) with the smallest
|
|
315
|
+
# sides still allowed is a lower bound for the remaining loop iterations
|
|
316
|
+
a_values.each do |a|
|
|
317
|
+
next unless beats_best.call([a, [a, min_b].max, [a, min_b, min_c].max])
|
|
318
|
+
values.each do |b|
|
|
319
|
+
next if b < [a, min_b].max - EPSILON
|
|
320
|
+
break unless beats_best.call([a, b, [b, min_c].max])
|
|
321
|
+
values.each do |c|
|
|
322
|
+
next if c < [b, min_c].max - EPSILON || a * b * c < min_vol - EPSILON
|
|
323
|
+
candidate = [a, b, c]
|
|
324
|
+
# c only grows from here, so neither limits nor cost can get better
|
|
325
|
+
break unless within_limits?(candidate, limits)
|
|
326
|
+
break unless beats_best.call(candidate)
|
|
327
|
+
|
|
328
|
+
return best if deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
|
|
329
|
+
return best if max_attempts && attempts >= max_attempts
|
|
330
|
+
attempts += 1
|
|
331
|
+
next unless fits_in_one?(candidate, items, pack_options)
|
|
332
|
+
|
|
333
|
+
best, best_cost = candidate, cost_of.call(candidate)
|
|
334
|
+
break
|
|
335
|
+
end
|
|
336
|
+
end
|
|
337
|
+
end
|
|
338
|
+
best
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
# Binary search the largest c in [min_c, cap] for which [min_a, min_b, c] still beats the best.
|
|
342
|
+
def largest_side_beating(cap, min_a, min_b, min_c, beats_best)
|
|
343
|
+
return min_c unless beats_best.call([min_a, min_b, min_c].sort)
|
|
344
|
+
lo, hi = min_c.to_f, cap.to_f
|
|
345
|
+
40.times do
|
|
346
|
+
mid = (lo + hi) / 2
|
|
347
|
+
beats_best.call([min_a, min_b, mid].sort) ? lo = mid : hi = mid
|
|
348
|
+
end
|
|
349
|
+
[hi, cap].min
|
|
350
|
+
end
|
|
351
|
+
|
|
352
|
+
# Possible container side lengths: subset sums of item sides up to `cap`.
|
|
353
|
+
# When there are too many (lots of different float sizes) they are rounded up
|
|
354
|
+
# to a grid, which only makes candidates slightly bigger, never invalid.
|
|
355
|
+
def side_values(sorted_dims, cap, max_values)
|
|
356
|
+
sums = { 0.0 => true }
|
|
357
|
+
grid = nil
|
|
358
|
+
sorted_dims.flatten.each do |d|
|
|
359
|
+
sums.keys.each do |v|
|
|
360
|
+
nv = v + d
|
|
361
|
+
next if nv > cap + EPSILON
|
|
362
|
+
nv = grid ? ((nv / grid).ceil * grid) : nv
|
|
363
|
+
sums[nv.round(6)] = true
|
|
364
|
+
end
|
|
365
|
+
if !grid && sums.size > max_values * 10
|
|
366
|
+
grid = cap / max_values
|
|
367
|
+
sums = sums.keys.map { |v| ((v / grid).ceil * grid).round(6) }.uniq.map { |v| [v, true] }.to_h
|
|
368
|
+
end
|
|
369
|
+
end
|
|
370
|
+
values = sums.keys.reject(&:zero?).sort
|
|
371
|
+
# keep the search bounded: at most max_values values spread over the range
|
|
372
|
+
values = values.each_slice((values.size.to_f / max_values).ceil).map(&:first) if values.size > max_values
|
|
373
|
+
values
|
|
374
|
+
end
|
|
375
|
+
|
|
376
|
+
# pack_options: split_strategies:, greedy_fallback: and optionally weight_limit:
|
|
377
|
+
def fits_in_one?(dimensions, items, pack_options = {})
|
|
378
|
+
options = pack_options.dup
|
|
379
|
+
container = { dimensions: dimensions, weight_limit: options.delete(:weight_limit) }
|
|
380
|
+
packing = pack(container: container, items: items, **options)
|
|
381
|
+
packing[:packings].size == 1 && packing[:errors].empty?
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
# result is a #pack result whose first packing is the one used for this box
|
|
385
|
+
def box_result(candidate, result)
|
|
386
|
+
packing = result[:packings].first
|
|
387
|
+
{
|
|
388
|
+
box: candidate[:box],
|
|
389
|
+
container_dimensions: result[:container_dimensions],
|
|
390
|
+
placements: with_steps(packing[:placements]),
|
|
391
|
+
weight: packing[:weight],
|
|
392
|
+
cost: candidate[:cost]
|
|
393
|
+
}
|
|
394
|
+
end
|
|
395
|
+
|
|
396
|
+
# placements in their original order, each with step: and support: added
|
|
397
|
+
def with_steps(placements)
|
|
398
|
+
order = placements.each_index.sort_by do |i|
|
|
399
|
+
pos = placements[i][:position]
|
|
400
|
+
[pos[2].round(6), pos[0].round(6), pos[1].round(6), i]
|
|
401
|
+
end
|
|
402
|
+
step = {}
|
|
403
|
+
order.each_with_index { |i, s| step[i] = s + 1 }
|
|
404
|
+
placements.each_with_index.map { |pl, i| pl.merge(step: step[i], support: support_ratio(pl, placements)) }
|
|
405
|
+
end
|
|
406
|
+
|
|
407
|
+
def packed_volume(packing)
|
|
408
|
+
packing[:placements].sum { |pl| volume(pl[:dimensions]) }
|
|
409
|
+
end
|
|
410
|
+
|
|
411
|
+
def validate_split_strategies!(strategies)
|
|
412
|
+
allowed = [:legacy, :max_space, 0, 1, 2, 3, 4, 5]
|
|
413
|
+
unless strategies.is_a?(Array) && !strategies.empty? && strategies.all? { |s| allowed.include?(s) }
|
|
414
|
+
raise ArgumentError, "split_strategies must be a non-empty array of #{allowed.inspect}"
|
|
415
|
+
end
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
def length_plus_girth(dimensions)
|
|
419
|
+
a, b, c = dimensions.sort
|
|
420
|
+
c + 2 * (a + b)
|
|
421
|
+
end
|
|
422
|
+
|
|
423
|
+
def default_cost(dimensions)
|
|
424
|
+
[volume(dimensions).round(6), length_plus_girth(dimensions).round(6)]
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
def within_limits?(dimensions, limits)
|
|
428
|
+
return false if dimensions.nil?
|
|
429
|
+
return false if limits[:max_length] && dimensions.max > limits[:max_length] + EPSILON
|
|
430
|
+
return false if limits[:max_length_plus_girth] && length_plus_girth(dimensions) > limits[:max_length_plus_girth] + EPSILON
|
|
431
|
+
true
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
def validate_non_negative!(name, value)
|
|
435
|
+
return if value.nil?
|
|
436
|
+
raise ArgumentError, "#{name} must be a non-negative number" unless value.is_a?(Numeric) && value >= 0
|
|
437
|
+
end
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def pack_with_strategy(container_dimensions, items, weight_limit, strategy)
|
|
4
441
|
packings = []
|
|
5
442
|
errors = []
|
|
443
|
+
|
|
6
444
|
# pack from biggest to smallest
|
|
7
|
-
items.sort_by { |h| h[:dimensions].sort.reverse }.reverse.each do |item|
|
|
8
|
-
|
|
9
|
-
|
|
445
|
+
items.sort_by { |h| valid_dimensions?(h[:dimensions]) ? h[:dimensions].sort.reverse : [] }.reverse.each do |item|
|
|
446
|
+
unless valid_dimensions?(item[:dimensions])
|
|
447
|
+
errors << "Item: #{item} has invalid dimensions"
|
|
448
|
+
next
|
|
449
|
+
end
|
|
450
|
+
|
|
451
|
+
item_weight = item[:weight].to_f
|
|
452
|
+
# If the item is just too heavy for the container lets give up on this
|
|
453
|
+
if item_weight > weight_limit
|
|
10
454
|
errors << "Item: #{item} is too heavy for container"
|
|
11
455
|
next
|
|
12
456
|
end
|
|
13
457
|
|
|
14
|
-
# Need a bool so we can break out nested loops once it's been packed
|
|
15
458
|
item_has_been_packed = false
|
|
16
459
|
|
|
17
460
|
packings.each do |packing|
|
|
18
|
-
# If this
|
|
461
|
+
# If this packing is going to be too heavy with this
|
|
19
462
|
# item as well then skip on to the next packing
|
|
20
|
-
next if packing[:weight]
|
|
463
|
+
next if packing[:weight] + item_weight > weight_limit + EPSILON
|
|
21
464
|
|
|
22
|
-
# remove volume size = 0 (not possible to pack)
|
|
23
|
-
packing[:spaces].reject! { |space| space[:dimensions].inject(:*) == 0 }
|
|
24
465
|
# try minimum space first
|
|
25
466
|
packing[:spaces].sort_by { |h| h[:dimensions].sort }.each do |space|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
packing[:placements] += [placement]
|
|
32
|
-
packing[:weight] += item[:weight].to_f
|
|
33
|
-
packing[:spaces] -= [space]
|
|
34
|
-
packing[:spaces] += break_up_space(space, placement)
|
|
467
|
+
next unless placement = place(item, space, packing[:placements])
|
|
468
|
+
packing[:placements] << placement
|
|
469
|
+
packing[:weight] += item_weight
|
|
470
|
+
packing[:spaces].delete(space)
|
|
471
|
+
packing[:spaces].concat(break_up_space(space, placement, strategy))
|
|
35
472
|
item_has_been_packed = true
|
|
36
473
|
break
|
|
37
474
|
end
|
|
@@ -41,80 +478,129 @@ module EasyBoxPacker
|
|
|
41
478
|
|
|
42
479
|
# Can't fit in any of the spaces for the current packings
|
|
43
480
|
# so lets try a new space the size of the container
|
|
44
|
-
space = {
|
|
45
|
-
dimensions: container[:dimensions].sort.reverse,
|
|
46
|
-
position: [0, 0, 0]
|
|
47
|
-
}
|
|
481
|
+
space = { dimensions: container_dimensions, position: [0, 0, 0] }
|
|
48
482
|
placement = place(item, space)
|
|
49
483
|
|
|
50
|
-
# If it can't be placed in this space, then it's just
|
|
51
|
-
# too big for the container and we should abandon hope
|
|
52
484
|
unless placement
|
|
53
485
|
errors << "Item: #{item} cannot be placed in container"
|
|
54
486
|
next
|
|
55
487
|
end
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
packings += [{
|
|
488
|
+
|
|
489
|
+
packings << {
|
|
59
490
|
placements: [placement],
|
|
60
|
-
weight:
|
|
61
|
-
spaces: break_up_space(space, placement)
|
|
62
|
-
}
|
|
491
|
+
weight: item_weight,
|
|
492
|
+
spaces: break_up_space(space, placement, strategy)
|
|
493
|
+
}
|
|
63
494
|
end
|
|
64
495
|
|
|
65
|
-
|
|
66
|
-
{ packings: generate_packing_for_greedy_box(items), errors: [] }
|
|
67
|
-
else
|
|
68
|
-
{ packings: packings, errors: errors }
|
|
69
|
-
end
|
|
496
|
+
{ packings: packings, errors: errors, container_dimensions: container_dimensions }
|
|
70
497
|
end
|
|
71
498
|
|
|
72
|
-
def
|
|
73
|
-
|
|
74
|
-
|
|
499
|
+
def constrained?(items)
|
|
500
|
+
items.any? { |i| i.is_a?(Hash) && (i[:upright] || i[:fragile]) }
|
|
501
|
+
end
|
|
75
502
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
503
|
+
# The container stood on each of its sides: [length, width, up], longest first.
|
|
504
|
+
def container_frames(dimensions)
|
|
505
|
+
l, w, h = dimensions.sort.reverse
|
|
506
|
+
[[l, w, h], [l, h, w], [w, h, l]].uniq
|
|
507
|
+
end
|
|
79
508
|
|
|
80
|
-
|
|
81
|
-
|
|
509
|
+
def footprint_overlap(a_pos, a_dims, b_pos, b_dims)
|
|
510
|
+
(0..1).map do |k|
|
|
511
|
+
[[a_pos[k] + a_dims[k], b_pos[k] + b_dims[k]].min - [a_pos[k], b_pos[k]].max, 0].max
|
|
512
|
+
end.inject(:*)
|
|
513
|
+
end
|
|
82
514
|
|
|
83
|
-
|
|
84
|
-
|
|
515
|
+
# true when a box at position/dims would be on top of a fragile item,
|
|
516
|
+
# or below anything when the item itself is fragile
|
|
517
|
+
def blocked_by_fragile?(item, position, dims, placements)
|
|
518
|
+
placements.any? do |pl|
|
|
519
|
+
next false unless footprint_overlap(position, dims, pl[:position], pl[:dimensions]) > EPSILON
|
|
520
|
+
top_of_pl = pl[:position][2] + pl[:dimensions][2]
|
|
521
|
+
top_of_item = position[2] + dims[2]
|
|
522
|
+
(pl[:item].is_a?(Hash) && pl[:item][:fragile] && position[2] >= top_of_pl - EPSILON) ||
|
|
523
|
+
(item[:fragile] && pl[:position][2] >= top_of_item - EPSILON)
|
|
85
524
|
end
|
|
525
|
+
end
|
|
86
526
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
select_container = possible_containers.map { |a| a.sort }.sort_by { |a| [a.inject(&:*), a.inject(&:+)] }.each do |c|
|
|
96
|
-
packing = pack(
|
|
97
|
-
container: { dimensions: c },
|
|
98
|
-
items: items)
|
|
99
|
-
break c if packing[:packings].size == 1
|
|
527
|
+
def support_ratio(placement, placements)
|
|
528
|
+
z = placement[:position][2]
|
|
529
|
+
return 1.0 if z <= EPSILON
|
|
530
|
+
area = placement[:dimensions][0] * placement[:dimensions][1]
|
|
531
|
+
supported = placements.sum do |pl|
|
|
532
|
+
next 0 if pl.equal?(placement) || (pl[:position][2] + pl[:dimensions][2] - z).abs > EPSILON
|
|
533
|
+
footprint_overlap(placement[:position], placement[:dimensions], pl[:position], pl[:dimensions])
|
|
100
534
|
end
|
|
101
|
-
|
|
535
|
+
[supported / area.to_f, 1.0].min.round(4)
|
|
102
536
|
end
|
|
103
537
|
|
|
104
|
-
|
|
538
|
+
def validate_container!(container)
|
|
539
|
+
unless container.is_a?(Hash) && valid_dimensions?(container[:dimensions])
|
|
540
|
+
raise ArgumentError, "invalid container dimensions: #{container.inspect}"
|
|
541
|
+
end
|
|
542
|
+
end
|
|
543
|
+
|
|
544
|
+
def valid_dimensions?(dimensions)
|
|
545
|
+
dimensions.is_a?(Array) && dimensions.size == 3 &&
|
|
546
|
+
dimensions.all? { |d| d.is_a?(Numeric) && d.finite? && d > 0 }
|
|
547
|
+
end
|
|
548
|
+
|
|
549
|
+
def weight_limit_of(container)
|
|
550
|
+
# No weight_limit means no weight restriction.
|
|
551
|
+
container[:weight_limit].nil? ? Float::INFINITY : container[:weight_limit].to_f
|
|
552
|
+
end
|
|
553
|
+
|
|
554
|
+
# Containers are returned as floats sorted ascending, e.g. [2.0, 2.0, 3.0].
|
|
555
|
+
def normalize(dimensions)
|
|
556
|
+
dimensions.map(&:to_f).sort
|
|
557
|
+
end
|
|
558
|
+
|
|
559
|
+
def aspect_ratio(dimensions)
|
|
560
|
+
dimensions.max.to_f / dimensions.min
|
|
561
|
+
end
|
|
562
|
+
|
|
563
|
+
# Use the greedy box when nothing else was found, when it fits inside the
|
|
564
|
+
# selected container, or when it is both smaller and no more elongated.
|
|
565
|
+
def prefer_greedy_box?(greedy_box, selected)
|
|
566
|
+
return true if selected.nil?
|
|
567
|
+
g = greedy_box.sort
|
|
568
|
+
s = selected.sort
|
|
569
|
+
return true if (0..2).all? { |i| s[i] + EPSILON >= g[i] }
|
|
570
|
+
volume(g) <= volume(s) + EPSILON && aspect_ratio(g) <= aspect_ratio(s) + EPSILON
|
|
571
|
+
end
|
|
572
|
+
|
|
573
|
+
def volume(dimensions)
|
|
574
|
+
dimensions.inject(:*)
|
|
575
|
+
end
|
|
105
576
|
|
|
106
577
|
def std(contents)
|
|
107
578
|
n = contents.size
|
|
108
|
-
contents.map
|
|
109
|
-
mean =
|
|
110
|
-
sum_sqr =
|
|
111
|
-
Math.sqrt(((sum_sqr - n * mean * mean)/(n-1)).abs)
|
|
579
|
+
values = contents.map(&:to_f)
|
|
580
|
+
mean = values.sum / n
|
|
581
|
+
sum_sqr = values.map { |x| x * x }.sum
|
|
582
|
+
Math.sqrt(((sum_sqr - n * mean * mean) / (n - 1)).abs)
|
|
112
583
|
end
|
|
113
584
|
|
|
114
|
-
|
|
115
|
-
|
|
585
|
+
# Grow a container by adding items one at a time on each face, keeping
|
|
586
|
+
# the most "cube like" and the smallest candidates at each step (beam search).
|
|
587
|
+
def find_possible_containers(container:, items:, min_vol:, beam_width: SEARCH_BEAM_WIDTH)
|
|
588
|
+
possible_containers = []
|
|
589
|
+
frontier = [container.sort]
|
|
590
|
+
|
|
591
|
+
items.drop(1).each do |item|
|
|
592
|
+
candidates = frontier.flat_map { |c| grow_container(c, item) }.uniq
|
|
593
|
+
candidates.each { |c| possible_containers << c if volume(c) >= min_vol }
|
|
594
|
+
|
|
595
|
+
frontier = candidates.sort_by { |a| [std(a), volume(a), a.inject(:+)] }.first(beam_width)
|
|
596
|
+
end
|
|
597
|
+
|
|
598
|
+
possible_containers.uniq
|
|
599
|
+
end
|
|
600
|
+
|
|
601
|
+
def grow_container(container, item)
|
|
116
602
|
c_length, c_width, c_height = container.sort.reverse
|
|
117
|
-
b_length, b_width, b_height =
|
|
603
|
+
b_length, b_width, b_height = item.sort.reverse
|
|
118
604
|
c_permutations = [
|
|
119
605
|
[c_width, c_height, c_length],
|
|
120
606
|
[c_length, c_width, c_height],
|
|
@@ -126,38 +612,18 @@ module EasyBoxPacker
|
|
|
126
612
|
[b_length, b_height, b_width]
|
|
127
613
|
]
|
|
128
614
|
|
|
129
|
-
|
|
130
|
-
# (1) loops base_container 3 rotations
|
|
615
|
+
result = []
|
|
131
616
|
c_permutations.each do |c_perm|
|
|
132
|
-
# (2) try to puts items to 3 points, then it will create 3 different possible containers
|
|
133
617
|
b_permutations.each do |b_perm|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
end
|
|
138
|
-
end
|
|
139
|
-
removed_tried_container = tmp_possible_containers.map { |a| a.sort }.uniq - possible_containers - invalid_containers
|
|
140
|
-
|
|
141
|
-
return unless removed_tried_container.any?
|
|
142
|
-
# (3) loop all container from smallest spaces to biggest space
|
|
143
|
-
removed_tried_container.sort_by { |a| [a.inject(&:*), a.inject(&:+)] }.each do |cont|
|
|
144
|
-
# (4) next unless l * w * h >= minimum_space
|
|
145
|
-
if cont.inject(&:*) >= min_vol
|
|
146
|
-
possible_containers << cont
|
|
147
|
-
# else
|
|
148
|
-
# puts "invalid: #{cont}"
|
|
149
|
-
# invalid_containers << cont
|
|
150
|
-
# find_possible_container(possible_containers: possible_containers, invalid_containers: invalid_containers, container: cont, items: items, item_index: item_index + 1, min_vol: min_vol)
|
|
618
|
+
result << [ c_perm[0] + b_perm[0], [c_perm[1], b_perm[1]].max, [c_perm[2], b_perm[2]].max]
|
|
619
|
+
result << [[c_perm[0], b_perm[0]].max, c_perm[1] + b_perm[1], [c_perm[2], b_perm[2]].max]
|
|
620
|
+
result << [[c_perm[0], b_perm[0]].max, [c_perm[1], b_perm[1]].max, c_perm[2] + b_perm[2]]
|
|
151
621
|
end
|
|
152
622
|
end
|
|
153
|
-
|
|
154
|
-
minimum_std = removed_tried_container.sort_by { |a| [std(a), a.inject(&:*), a.inject(&:+)] }.first
|
|
155
|
-
[minimum_std].uniq.compact.each do |cont|
|
|
156
|
-
find_possible_container(possible_containers: possible_containers, invalid_containers: invalid_containers, container: cont, items: items, item_index: item_index + 1, min_vol: min_vol)
|
|
157
|
-
end
|
|
623
|
+
result.map { |a| a.map(&:to_f).sort }
|
|
158
624
|
end
|
|
159
625
|
|
|
160
|
-
def place(item, space)
|
|
626
|
+
def place(item, space, placements = [])
|
|
161
627
|
item_length, item_width, item_height = item[:dimensions].sort.reverse
|
|
162
628
|
|
|
163
629
|
permutations = [
|
|
@@ -169,30 +635,51 @@ module EasyBoxPacker
|
|
|
169
635
|
[item_length, item_height, item_width]
|
|
170
636
|
]
|
|
171
637
|
|
|
638
|
+
if item[:upright]
|
|
639
|
+
up = item[:dimensions][2]
|
|
640
|
+
permutations = permutations.select { |perm| (perm[2] - up).abs <= EPSILON }
|
|
641
|
+
end
|
|
642
|
+
|
|
172
643
|
possible_rotations_and_margins = []
|
|
173
644
|
|
|
174
645
|
permutations.each do |perm|
|
|
175
646
|
# Skip if the item does not fit with this orientation
|
|
176
|
-
next unless perm[
|
|
177
|
-
perm[1] <= space[:dimensions][1] &&
|
|
178
|
-
perm[2] <= space[:dimensions][2]
|
|
647
|
+
next unless (0..2).all? { |i| perm[i] <= space[:dimensions][i] + EPSILON }
|
|
179
648
|
|
|
180
|
-
possible_margin
|
|
649
|
+
possible_margin = (0..2).map { |i| space[:dimensions][i] - perm[i] }
|
|
181
650
|
possible_rotations_and_margins << { margin: possible_margin, rotation: perm }
|
|
182
651
|
end
|
|
183
652
|
|
|
184
653
|
# select rotation with smallest margin
|
|
185
|
-
|
|
654
|
+
ranked = possible_rotations_and_margins.sort_by { |a| a[:margin].sort }
|
|
655
|
+
check_fragile = item[:fragile] || placements.any? { |pl| pl[:item].is_a?(Hash) && pl[:item][:fragile] }
|
|
656
|
+
final = check_fragile ? ranked.find { |a| !blocked_by_fragile?(item, space[:position], a[:rotation], placements) } : ranked.first
|
|
186
657
|
return unless final
|
|
187
|
-
|
|
658
|
+
{
|
|
188
659
|
dimensions: final[:rotation],
|
|
189
660
|
position: space[:position],
|
|
190
|
-
weight: item[:weight].to_f
|
|
661
|
+
weight: item[:weight].to_f,
|
|
662
|
+
item: item
|
|
191
663
|
}
|
|
192
664
|
end
|
|
193
665
|
|
|
194
|
-
def break_up_space(space, placement)
|
|
195
|
-
|
|
666
|
+
def break_up_space(space, placement, strategy = :legacy)
|
|
667
|
+
options = split_options(space, placement)
|
|
668
|
+
# original heuristic: compare the sorted dimensions of each option's spaces
|
|
669
|
+
ranked = options.sort_by { |a| a.map { |aa| aa[:dimensions].sort } }
|
|
670
|
+
chosen =
|
|
671
|
+
case strategy
|
|
672
|
+
when :legacy then ranked.last
|
|
673
|
+
# keep the largest single free block; ties fall back to :legacy order
|
|
674
|
+
when :max_space then ranked.reverse.max_by { |a| a.map { |aa| volume(aa[:dimensions]) }.max }
|
|
675
|
+
else options[strategy]
|
|
676
|
+
end
|
|
677
|
+
# drop empty (zero / float-noise) spaces, they can never hold anything
|
|
678
|
+
chosen.reject { |s| s[:dimensions].any? { |d| d <= EPSILON } }
|
|
679
|
+
end
|
|
680
|
+
|
|
681
|
+
def split_options(space, placement)
|
|
682
|
+
[
|
|
196
683
|
# HEIGHT SPACE => WIDTH => LENGTH
|
|
197
684
|
[
|
|
198
685
|
{
|
|
@@ -428,31 +915,45 @@ module EasyBoxPacker
|
|
|
428
915
|
}
|
|
429
916
|
]
|
|
430
917
|
]
|
|
431
|
-
# PICK biggest
|
|
432
|
-
return_possible_spaces.sort_by { |a| a.map {|aa| aa[:dimensions].sort}}.last
|
|
433
918
|
end
|
|
434
919
|
|
|
920
|
+
# Smallest box that holds every item laid flat and stacked on top of each other.
|
|
435
921
|
def item_greedy_box(items)
|
|
436
|
-
array_of_lwh
|
|
437
|
-
items_max_length
|
|
438
|
-
items_max_width
|
|
439
|
-
|
|
922
|
+
array_of_lwh = items.map { |i| i[:dimensions].sort.reverse }
|
|
923
|
+
items_max_length = array_of_lwh.map { |x| x[0] }.max
|
|
924
|
+
items_max_width = array_of_lwh.map { |x| x[1] }.max
|
|
925
|
+
# round only to remove float noise (e.g. 20.099999999999998), never truncate real size
|
|
926
|
+
items_total_height = array_of_lwh.map { |x| x[2] }.sum.round(6)
|
|
440
927
|
[items_max_length, items_max_width, items_total_height]
|
|
441
928
|
end
|
|
442
929
|
|
|
443
930
|
def check_container_is_bigger_than_greedy_box(container, items)
|
|
444
931
|
c = container[:dimensions].sort.reverse
|
|
445
|
-
greedy_box = item_greedy_box(items)
|
|
446
|
-
|
|
932
|
+
greedy_box = item_greedy_box(items).sort.reverse
|
|
933
|
+
(0..2).all? { |i| c[i] + EPSILON >= greedy_box[i] } &&
|
|
934
|
+
weight_limit_of(container) + EPSILON >= items.sum { |i| i[:weight].to_f }
|
|
447
935
|
end
|
|
448
936
|
|
|
449
|
-
|
|
450
|
-
|
|
937
|
+
# Stack items flat along the greedy box's height, then map the result into
|
|
938
|
+
# the container's frame (dimensions sorted descending) like #pack does.
|
|
939
|
+
def generate_packing_for_greedy_box(container, items)
|
|
940
|
+
greedy_box = item_greedy_box(items)
|
|
941
|
+
# axis_map[k] = greedy box axis that lies along container axis k
|
|
942
|
+
axis_map = [0, 1, 2].sort_by { |i| [-greedy_box[i], i] }
|
|
943
|
+
|
|
944
|
+
return_h = { placements: [], weight: 0.0, spaces: [] }
|
|
451
945
|
height = 0
|
|
452
946
|
items.each do |i|
|
|
453
|
-
|
|
947
|
+
dims = i[:dimensions].sort.reverse
|
|
948
|
+
position = [0, 0, height]
|
|
949
|
+
return_h[:placements] << {
|
|
950
|
+
dimensions: axis_map.map { |a| dims[a] },
|
|
951
|
+
position: axis_map.map { |a| position[a] },
|
|
952
|
+
weight: i[:weight].to_f,
|
|
953
|
+
item: i
|
|
954
|
+
}
|
|
454
955
|
return_h[:weight] += i[:weight].to_f
|
|
455
|
-
height +=
|
|
956
|
+
height += dims[2]
|
|
456
957
|
end
|
|
457
958
|
[return_h]
|
|
458
959
|
end
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: easy-box-packer
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.0
|
|
4
|
+
version: 0.4.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Aloha Chen
|
|
8
|
-
autorequire:
|
|
8
|
+
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date:
|
|
11
|
+
date: 2026-11-19 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: rspec
|
|
@@ -16,35 +16,15 @@ dependencies:
|
|
|
16
16
|
requirements:
|
|
17
17
|
- - "~>"
|
|
18
18
|
- !ruby/object:Gem::Version
|
|
19
|
-
version: '3.
|
|
20
|
-
- - ">="
|
|
21
|
-
- !ruby/object:Gem::Version
|
|
22
|
-
version: 3.1.0
|
|
19
|
+
version: '3.13'
|
|
23
20
|
type: :development
|
|
24
21
|
prerelease: false
|
|
25
22
|
version_requirements: !ruby/object:Gem::Requirement
|
|
26
23
|
requirements:
|
|
27
24
|
- - "~>"
|
|
28
25
|
- !ruby/object:Gem::Version
|
|
29
|
-
version: '3.
|
|
30
|
-
|
|
31
|
-
- !ruby/object:Gem::Version
|
|
32
|
-
version: 3.1.0
|
|
33
|
-
- !ruby/object:Gem::Dependency
|
|
34
|
-
name: pry
|
|
35
|
-
requirement: !ruby/object:Gem::Requirement
|
|
36
|
-
requirements:
|
|
37
|
-
- - ">="
|
|
38
|
-
- !ruby/object:Gem::Version
|
|
39
|
-
version: '0'
|
|
40
|
-
type: :development
|
|
41
|
-
prerelease: false
|
|
42
|
-
version_requirements: !ruby/object:Gem::Requirement
|
|
43
|
-
requirements:
|
|
44
|
-
- - ">="
|
|
45
|
-
- !ruby/object:Gem::Version
|
|
46
|
-
version: '0'
|
|
47
|
-
description:
|
|
26
|
+
version: '3.13'
|
|
27
|
+
description:
|
|
48
28
|
email: y.alohac@gmail.com
|
|
49
29
|
executables: []
|
|
50
30
|
extensions: []
|
|
@@ -56,8 +36,10 @@ files:
|
|
|
56
36
|
homepage: https://github.com/alChaCC/easy-box-packer
|
|
57
37
|
licenses:
|
|
58
38
|
- MIT
|
|
59
|
-
metadata:
|
|
60
|
-
|
|
39
|
+
metadata:
|
|
40
|
+
source_code_uri: https://github.com/alChaCC/easy-box-packer
|
|
41
|
+
rubygems_mfa_required: 'true'
|
|
42
|
+
post_install_message:
|
|
61
43
|
rdoc_options: []
|
|
62
44
|
require_paths:
|
|
63
45
|
- "."
|
|
@@ -65,16 +47,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
|
|
|
65
47
|
requirements:
|
|
66
48
|
- - ">="
|
|
67
49
|
- !ruby/object:Gem::Version
|
|
68
|
-
version: '
|
|
50
|
+
version: '2.7'
|
|
69
51
|
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
70
52
|
requirements:
|
|
71
53
|
- - ">="
|
|
72
54
|
- !ruby/object:Gem::Version
|
|
73
55
|
version: '0'
|
|
74
56
|
requirements: []
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
signing_key:
|
|
57
|
+
rubygems_version: 3.1.6
|
|
58
|
+
signing_key:
|
|
78
59
|
specification_version: 4
|
|
79
60
|
summary: 3D bin-packing with weight limit using first-fit decreasing algorithm and
|
|
80
61
|
empty maximal spaces
|