Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
2d_orthogonal_packing.cc
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
15
16#include <algorithm>
17#include <cstdint>
18#include <limits>
19#include <optional>
20#include <string>
21#include <tuple>
22#include <utility>
23#include <vector>
24
25#include "absl/log/check.h"
26#include "absl/numeric/bits.h"
27#include "absl/random/distributions.h"
28#include "absl/types/span.h"
33#include "ortools/sat/util.h"
34#include "ortools/util/bitset.h"
35
36namespace operations_research {
37namespace sat {
38
41 if (!VLOG_IS_ON(1)) return;
42 std::vector<std::pair<std::string, int64_t>> stats;
43 stats.push_back(
44 {"OrthogonalPackingInfeasibilityDetector/called", num_calls_});
45 stats.push_back(
46 {"OrthogonalPackingInfeasibilityDetector/conflicts", num_conflicts_});
47 stats.push_back({"OrthogonalPackingInfeasibilityDetector/dff0_conflicts",
48 num_conflicts_dff0_});
49 stats.push_back({"OrthogonalPackingInfeasibilityDetector/dff2_conflicts",
50 num_conflicts_dff2_});
51 stats.push_back({"OrthogonalPackingInfeasibilityDetector/trivial_conflicts",
52 num_trivial_conflicts_});
53 stats.push_back({"OrthogonalPackingInfeasibilityDetector/conflicts_two_items",
54 num_conflicts_two_items_});
55 stats.push_back({"OrthogonalPackingInfeasibilityDetector/no_energy_conflict",
56 num_scheduling_possible_});
57 stats.push_back({"OrthogonalPackingInfeasibilityDetector/brute_force_calls",
58 num_brute_force_calls_});
59 stats.push_back(
60 {"OrthogonalPackingInfeasibilityDetector/brute_force_conflicts",
61 num_brute_force_conflicts_});
62 stats.push_back(
63 {"OrthogonalPackingInfeasibilityDetector/brute_force_relaxations",
64 num_brute_force_relaxation_});
65
66 shared_stats_->AddStats(stats);
67}
68
69namespace {
70std::optional<std::pair<int, int>> FindPairwiseConflict(
71 absl::Span<const IntegerValue> sizes_x,
72 absl::Span<const IntegerValue> sizes_y,
73 std::pair<IntegerValue, IntegerValue> bounding_box_size,
74 absl::Span<const int> index_by_decreasing_x_size,
75 absl::Span<const int> index_by_decreasing_y_size) {
76 // Look for pairwise incompatible pairs by using the logic such conflict can
77 // only happen between a "tall" item a "wide" item.
78 int x_idx = 0;
79 int y_idx = 0;
80 while (x_idx < index_by_decreasing_x_size.size() &&
81 y_idx < index_by_decreasing_y_size.size()) {
82 if (index_by_decreasing_x_size[x_idx] ==
83 index_by_decreasing_y_size[y_idx]) {
84 if (sizes_x[index_by_decreasing_x_size[x_idx]] >
85 sizes_y[index_by_decreasing_x_size[x_idx]]) {
86 y_idx++;
87 } else {
88 x_idx++;
89 }
90 continue;
91 }
92 const bool overlap_on_x = (sizes_x[index_by_decreasing_x_size[x_idx]] +
93 sizes_x[index_by_decreasing_y_size[y_idx]] >
94 bounding_box_size.first);
95 const bool overlap_on_y = (sizes_y[index_by_decreasing_x_size[x_idx]] +
96 sizes_y[index_by_decreasing_y_size[y_idx]] >
97 bounding_box_size.second);
98 if (overlap_on_x && overlap_on_y) {
99 return std::make_pair(index_by_decreasing_x_size[x_idx],
100 index_by_decreasing_y_size[y_idx]);
101 } else if (overlap_on_x) {
102 x_idx++;
103 } else if (overlap_on_y) {
104 y_idx++;
105 } else {
106 y_idx++;
107 }
108 }
109 return std::nullopt;
110}
111
112IntegerValue RoundingLowestInverse(IntegerValue y, IntegerValue c_k,
113 IntegerValue max_x, IntegerValue k) {
114 DCHECK_GE(y, 0);
115 DCHECK_LE(y, 2 * c_k);
116 IntegerValue ret = std::numeric_limits<IntegerValue>::max();
117
118 // Are we in the case 2 * x == max_x_?
119 if (y <= c_k && (max_x.value() & 1) == 0) {
120 const IntegerValue inverse_mid = max_x / 2;
121 ret = std::min(ret, inverse_mid);
122 if (y == c_k && y.value() & 1) {
123 // This is the only valid case for odd x.
124 return ret;
125 }
126 }
127
128 // The "perfect odd" case is handled above, round up y to an even value.
129 y += y.value() & 1;
130
131 // Check the case 2 * x > max_x_.
132 const IntegerValue inverse_high = max_x - k * (c_k - y / 2);
133 if (2 * inverse_high > max_x) {
134 // We have an inverse in this domain, let's find its minimum value (when
135 // the division rounds down the most) but don't let it go outside the
136 // domain.
137 const IntegerValue lowest_inverse_high =
138 std::max(max_x / 2 + 1, inverse_high - k + 1);
139 ret = std::min(ret, lowest_inverse_high);
140 }
141
142 // Check the case 2 * x < max_x_.
143 const IntegerValue inverse_low = k * y / 2;
144 if (2 * inverse_low < max_x) {
145 ret = std::min(ret, inverse_low);
146 }
147 return ret;
148}
149} // namespace
150
151IntegerValue RoundingDualFeasibleFunction::LowestInverse(IntegerValue y) const {
152 return RoundingLowestInverse(y, c_k_, max_x_, k_);
153}
154
156 IntegerValue y) const {
157 return RoundingLowestInverse(y, c_k_, max_x_, IntegerValue(1) << log2_k_);
158}
159
160// Check for conflict using the `f_0^k` dual feasible function (see
161// documentation for DualFeasibleFunctionF0). This function tries all possible
162// values of the `k` parameter and returns the best conflict found (according to
163// OrthogonalPackingResult::IsBetterThan) if any.
164//
165// The current implementation is a bit more general than a simple check using
166// f_0 described above. This implementation can take a function g(x) that is
167// non-decreasing and satisfy g(0)=0 and it will check for conflict using
168// g(f_0^k(x)) for all values of k, but without recomputing g(x) `k` times. This
169// is handy if g() is a DFF that is slow to compute. g(x) is described by the
170// vector g_x[i] = g(sizes_x[i]) and the variable g_max = g(x_bb_size).
171//
172// The algorithm is the same if we swap the x and y dimension.
173OrthogonalPackingResult OrthogonalPackingInfeasibilityDetector::GetDffConflict(
174 absl::Span<const IntegerValue> sizes_x,
175 absl::Span<const IntegerValue> sizes_y,
176 absl::Span<const int> index_by_decreasing_x_size,
177 absl::Span<const IntegerValue> g_x, IntegerValue g_max,
178 IntegerValue x_bb_size, IntegerValue total_energy, IntegerValue bb_area,
179 IntegerValue* best_k) {
180 // If we found a conflict for a k parameter, which is rare, recompute the
181 // total used energy consumed by the items to find the minimal set of
182 // conflicting items.
183 int num_items = sizes_x.size();
184 auto build_result = [&sizes_x, &sizes_y, num_items, &x_bb_size, &bb_area,
185 &g_max, &g_x](const IntegerValue k) {
186 std::vector<std::pair<int, IntegerValue>> index_to_energy;
187 index_to_energy.reserve(num_items);
188 for (int i = 0; i < num_items; i++) {
189 IntegerValue point_value;
190 if (sizes_x[i] > x_bb_size - k) {
191 point_value = g_max;
192 } else if (sizes_x[i] < k) {
193 continue;
194 } else {
195 point_value = g_x[i];
196 }
197 index_to_energy.push_back({i, point_value * sizes_y[i]});
198 }
199 std::sort(index_to_energy.begin(), index_to_energy.end(),
200 [](const std::pair<int, IntegerValue>& a,
201 const std::pair<int, IntegerValue>& b) {
202 return a.second > b.second;
203 });
204 IntegerValue recomputed_energy = 0;
205 for (int i = 0; i < index_to_energy.size(); i++) {
206 recomputed_energy += index_to_energy[i].second;
207 if (recomputed_energy > bb_area) {
208 OrthogonalPackingResult result(
210 result.conflict_type_ = OrthogonalPackingResult::ConflictType::DFF_F0;
211 result.items_participating_on_conflict_.resize(i + 1);
212 for (int j = 0; j <= i; j++) {
213 const int index = index_to_energy[j].first;
214 result.items_participating_on_conflict_[j] = {
215 .index = index,
216 .size_x = sizes_x[index],
217 .size_y = sizes_y[index]};
218 }
219 result.slack_ = 0;
220 return result;
221 }
222 }
223 LOG(FATAL) << "build_result called with no conflict";
224 };
225
226 // One thing we use in this implementation is that not all values of k are
227 // interesting: what can cause an energy conflict is increasing the size of
228 // the large items, removing the small ones makes it less constrained and we
229 // do it only to preserve correctness. Thus, it is enough to check the values
230 // of k that are just small enough to enlarge a large item. That means that
231 // large items and small ones are not symmetric with respect to what values of
232 // k are important.
233 IntegerValue current_energy = total_energy;
234 OrthogonalPackingResult best_result;
235 if (current_energy > bb_area) {
236 best_result = build_result(0);
237 *best_k = 0;
238 }
239 // We keep an index on the largest item yet-to-be enlarged and the smallest
240 // one yet-to-be removed.
241 int removing_item_index = index_by_decreasing_x_size.size() - 1;
242 int enlarging_item_index = 0;
243 while (enlarging_item_index < index_by_decreasing_x_size.size()) {
244 int index = index_by_decreasing_x_size[enlarging_item_index];
245 IntegerValue size = sizes_x[index];
246 // Note that since `size_x` is decreasing, we test increasingly large
247 // values of k. Also note that a item with size `k` cannot fit alongside
248 // an item with size `size_x`, but smaller ones can.
249 const IntegerValue k = x_bb_size - size + 1;
250 if (2 * k > x_bb_size) {
251 break;
252 }
253 // First, add the area contribution of enlarging the all the items of size
254 // exactly size_x. All larger items were already enlarged in the previous
255 // iterations.
256 do {
257 index = index_by_decreasing_x_size[enlarging_item_index];
258 size = sizes_x[index];
259 current_energy += (g_max - g_x[index]) * sizes_y[index];
260 enlarging_item_index++;
261 } while (enlarging_item_index < index_by_decreasing_x_size.size() &&
262 sizes_x[index_by_decreasing_x_size[enlarging_item_index]] == size);
263
264 // Now remove the area contribution of removing all the items smaller than
265 // k that were not removed before.
266 while (removing_item_index >= 0 &&
267 sizes_x[index_by_decreasing_x_size[removing_item_index]] < k) {
268 const int remove_idx = index_by_decreasing_x_size[removing_item_index];
269 current_energy -= g_x[remove_idx] * sizes_y[remove_idx];
270 removing_item_index--;
271 }
272
273 if (current_energy > bb_area) {
274 OrthogonalPackingResult current_result = build_result(k);
275 if (current_result.IsBetterThan(best_result)) {
276 best_result = current_result;
277 *best_k = k;
278 }
279 }
280 }
281 return best_result;
282}
283
284namespace {
285
286// Tries a simple heuristic to find a solution for the Resource-Constrained
287// Project Scheduling Problem (RCPSP). The RCPSP can be mapped to a
288// 2d bin packing where one dimension (say, x) is chosen to represent the time,
289// and every item is cut into items with size_x = 1 that must remain consecutive
290// in the x-axis but do not need to be aligned on the y axis. This is often
291// called the cumulative relaxation of the 2d bin packing problem.
292//
293// Bin-packing solution RCPSP solution
294// --------------- ---------------
295// | ********** | | ***** |
296// | ********** | | ***** |
297// | ##### | | **#####*** |
298// | ##### | | **#####*** |
299// --------------- ---------------
300//
301// One interesting property is if we find an energy conflict using a
302// superadditive function it means the problem is infeasible both interpreted as
303// a 2d bin packing and as a RCPSP problem. In practice, that means that if we
304// find a RCPSP solution for a 2d bin packing problem, there is no point on
305// using Maximal DFFs to search for energy conflicts.
306//
307// Returns true if it found a feasible solution to the RCPSP problem.
308bool FindHeuristicSchedulingSolution(
309 absl::Span<const IntegerValue> sizes,
310 absl::Span<const IntegerValue> demands,
311 absl::Span<const int> heuristic_order, IntegerValue global_end_max,
312 IntegerValue capacity_max,
313 std::vector<std::pair<IntegerValue, IntegerValue>>& profile,
314 std::vector<std::pair<IntegerValue, IntegerValue>>& new_profile) {
315 // The profile (and new profile) is a set of (time, capa_left) pairs, ordered
316 // by increasing time and capa_left.
317 profile.clear();
318 profile.emplace_back(kMinIntegerValue, capacity_max);
319 profile.emplace_back(kMaxIntegerValue, capacity_max);
320 IntegerValue start_of_previous_task = kMinIntegerValue;
321 for (int i = 0; i < heuristic_order.size(); i++) {
322 const IntegerValue event_size = sizes[heuristic_order[i]];
323 const IntegerValue event_demand = demands[heuristic_order[i]];
324 const IntegerValue event_start_min = 0;
325 const IntegerValue event_start_max = global_end_max - event_size;
326 const IntegerValue start_min =
327 std::max(event_start_min, start_of_previous_task);
328
329 // Iterate on the profile to find the step that contains start_min.
330 // Then push until we find a step with enough capacity.
331 int current = 0;
332 while (profile[current + 1].first <= start_min ||
333 profile[current].second < event_demand) {
334 ++current;
335 }
336
337 const IntegerValue actual_start =
338 std::max(start_min, profile[current].first);
339 start_of_previous_task = actual_start;
340
341 // Compatible with the event.start_max ?
342 if (actual_start > event_start_max) return false;
343
344 const IntegerValue actual_end = actual_start + event_size;
345
346 // No need to update the profile on the last loop.
347 if (i == heuristic_order.size() - 1) break;
348
349 // Update the profile.
350 new_profile.clear();
351 new_profile.push_back(
352 {actual_start, profile[current].second - event_demand});
353 ++current;
354
355 while (profile[current].first < actual_end) {
356 new_profile.push_back(
357 {profile[current].first, profile[current].second - event_demand});
358 ++current;
359 }
360
361 if (profile[current].first > actual_end) {
362 new_profile.push_back(
363 {actual_end, new_profile.back().second + event_demand});
364 }
365 while (current < profile.size()) {
366 new_profile.push_back(profile[current]);
367 ++current;
368 }
369 profile.swap(new_profile);
370 }
371 return true;
372}
373
374} // namespace
375
376// We want to find the minimum set of values of `k` that would always find a
377// conflict if there is a `k` for which it exists. In the literature it is
378// often implied (but not stated) that it is sufficient to test the values of
379// `k` that correspond to the size of an item. This is not true. To find the
380// minimum set of values of `k` we look for all values of `k` that are
381// "extreme": ie., the rounding on the division truncates the most (or the
382// least) amount, depending on the sign it appears in the formula.
383//
384// To find these extreme values, we look for all local minima of the energy
385// slack after applying the DFF (we multiply by `k` for convenience):
386// k * f_k(H) * W - sum_i k * f_k(h_i) * w_i
387// If this value ever becomes negative for a value of `k`, it must happen in a
388// local minimum. Then we use the fact that
389// k * floor(x / k) = x - x % k
390// and that x%k has a local minimum when k=x/i and a local maximum when k=1+x/i
391// for every integer i. The final finer point in the calculation is
392// realizing that if
393// sum_{i, h_i > H/2} w_i > W
394// then you have more "large" objects than it fits in the box, and you will
395// have a conflict using the DFF f_0 for l=H/2. So we can safely ignore this
396// case for the more expensive DFF f_2 calculation.
397void OrthogonalPackingInfeasibilityDetector::GetAllCandidatesForKForDff2(
398 absl::Span<const IntegerValue> sizes, IntegerValue bb_size,
399 IntegerValue sqrt_bb_size, Bitset64<IntegerValue>& candidates) {
400 // x_bb_size is less than 65536, so this fits in only 4kib.
401 candidates.ClearAndResize(bb_size / 2 + 2);
402
403 // `sqrt_bb_size` is lower than 256.
404 for (IntegerValue i = 2; i <= sqrt_bb_size; i++) {
405 candidates.Set(i);
406 }
407 for (int i = 1; i <= sqrt_bb_size; i++) {
408 const ::util::math::ConstantDivisor<uint16_t> div(i);
409 if (i > 1) {
410 candidates.Set(bb_size.value() / div);
411 }
412 for (int k = 0; k < sizes.size(); k++) {
413 IntegerValue size = sizes[k];
414 if (2 * size > bb_size && size < bb_size) {
415 candidates.Set((bb_size.value() - size.value() + 1) / div);
416 } else if (2 * size < bb_size) {
417 candidates.Set(size.value() / div);
418 }
419 }
420 }
421
422 // Remove some bogus candidates added by the logic above.
423 candidates.Clear(0);
424 candidates.Clear(1);
425
426 // Apply the nice result described on [1]: if we are testing the DFF
427 // f_2^k(f_0^l(x)) for all values of `l`, the only values of `k` greater than
428 // C/4 we need to test are {C/4+1, C/3+1}.
429 //
430 // In the same reference there is a proof that this way of composing f_0 and
431 // f_2 cover all possible ways of composing the two functions, including
432 // composing several times each.
433 //
434 // [1] F. Clautiaux, PhD thesis, hal/tel-00749411.
435 candidates.Resize(bb_size / 4 + 1); // Erase all >= C/4
436 candidates.Resize(bb_size / 3 + 2); // Make room for the two special values
437 candidates.Set(bb_size / 4 + 1);
438 if (bb_size > 3) {
439 candidates.Set(bb_size / 3 + 1);
440 }
441}
442
443// Check for conflict all combinations of the two Dual Feasible Functions f_0
444// (see documentation for GetDffConflict()) and f_2 (see documentation for
445// RoundingDualFeasibleFunction). More precisely, check whether there exist `l`
446// and `k` so that
447//
448// sum_i f_2^k(f_0^l(sizes_x[i])) * sizes_y[i] > f_2^k(f_0^l(x_bb_size)) *
449// y_bb_size
450//
451// The function returns the smallest subset of items enough to make the
452// inequality above true or an empty vector if impossible.
454OrthogonalPackingInfeasibilityDetector::CheckFeasibilityWithDualFunction2(
455 absl::Span<const IntegerValue> sizes_x,
456 absl::Span<const IntegerValue> sizes_y,
457 absl::Span<const int> index_by_decreasing_x_size, IntegerValue x_bb_size,
458 IntegerValue y_bb_size, int max_number_of_parameters_to_check) {
459 if (x_bb_size == 1) {
460 return OrthogonalPackingResult();
461 }
462 std::vector<IntegerValue> sizes_x_rescaled;
463 if (x_bb_size >= std::numeric_limits<uint16_t>::max()) {
464 // To do fast division we want our sizes to fit in a uint16_t. The simplest
465 // way of doing that is to just first apply this DFF with the right
466 // power-of-two value of the parameter.
467 const int log2_k =
468 absl::bit_width(static_cast<uint64_t>(x_bb_size.value() + 1)) - 16 + 1;
469 const RoundingDualFeasibleFunctionPowerOfTwo dff(x_bb_size, log2_k);
470 sizes_x_rescaled.resize(sizes_x.size());
471 for (int i = 0; i < sizes_x.size(); i++) {
472 sizes_x_rescaled[i] = dff(sizes_x[i]);
473 }
474 x_bb_size = dff(x_bb_size);
475 CHECK_LT(x_bb_size, std::numeric_limits<uint16_t>::max());
476 sizes_x = sizes_x_rescaled;
477 }
478
479 Bitset64<IntegerValue> candidates;
480 const IntegerValue sqrt_bb_size = FloorSquareRoot(x_bb_size.value());
481 int num_items = sizes_x.size();
482 const IntegerValue max_possible_number_of_parameters =
483 std::min(x_bb_size / 4 + 1, sqrt_bb_size * num_items);
484 if (5ull * max_number_of_parameters_to_check <
485 max_possible_number_of_parameters) {
486 // There are many more possible values than what we want to sample. It is
487 // not worth to pay the price of computing all optimal values to drop most
488 // of them, so let's just pick it randomly.
489 candidates.Resize(x_bb_size / 4 + 1);
490 int num_candidates = 0;
491 while (num_candidates < max_number_of_parameters_to_check) {
492 const IntegerValue pick =
493 absl::Uniform(random_, 1, x_bb_size.value() / 4);
494 if (!candidates.IsSet(pick)) {
495 candidates.Set(pick);
496 num_candidates++;
497 }
498 }
499 } else {
500 GetAllCandidatesForKForDff2(sizes_x, x_bb_size, sqrt_bb_size, candidates);
501
502 if (max_number_of_parameters_to_check < max_possible_number_of_parameters) {
503 // We might have produced too many candidates. Let's count them and if it
504 // is the case, sample them.
505 int count = 0;
506 for (auto it = candidates.begin(); it != candidates.end(); ++it) {
507 count++;
508 }
509 if (count > max_number_of_parameters_to_check) {
510 std::vector<IntegerValue> sampled_candidates(
511 max_number_of_parameters_to_check);
512 std::sample(candidates.begin(), candidates.end(),
513 sampled_candidates.begin(),
514 max_number_of_parameters_to_check, random_);
515 candidates.ClearAll();
516 for (const IntegerValue k : sampled_candidates) {
517 candidates.Set(k);
518 }
519 }
520 }
521 }
522 OrthogonalPackingResult best_result;
523
524 // Finally run our small loop to look for the conflict!
525 std::vector<IntegerValue> modified_sizes(num_items);
526 for (const IntegerValue k : candidates) {
527 const RoundingDualFeasibleFunction dff(x_bb_size, k);
528 IntegerValue energy = 0;
529 for (int i = 0; i < num_items; i++) {
530 modified_sizes[i] = dff(sizes_x[i]);
531 energy += modified_sizes[i] * sizes_y[i];
532 }
533 const IntegerValue modified_x_bb_size = dff(x_bb_size);
534 IntegerValue dff0_k;
535 auto dff0_res =
536 GetDffConflict(sizes_x, sizes_y, index_by_decreasing_x_size,
537 modified_sizes, modified_x_bb_size, x_bb_size, energy,
538 modified_x_bb_size * y_bb_size, &dff0_k);
539 if (dff0_res.result_ != OrthogonalPackingResult::Status::INFEASIBLE) {
540 continue;
541 }
542 DFFComposedF2F0 composed_dff(x_bb_size, dff0_k, k);
543 dff0_res.conflict_type_ = OrthogonalPackingResult::ConflictType::DFF_F2;
544 for (auto& item : dff0_res.items_participating_on_conflict_) {
545 item.size_x =
546 composed_dff.LowestInverse(composed_dff(sizes_x[item.index]));
547
548 // The new size should contribute by the same amount to the energy and
549 // correspond to smaller items.
550 DCHECK_EQ(composed_dff(item.size_x), composed_dff(sizes_x[item.index]));
551 DCHECK_LE(item.size_x, sizes_x[item.index]);
552
553 item.size_y = sizes_y[item.index];
554 }
555 if (dff0_res.IsBetterThan(best_result)) {
556 best_result = dff0_res;
557 }
558 }
559
560 return best_result;
561}
562
563bool OrthogonalPackingInfeasibilityDetector::RelaxConflictWithBruteForce(
565 std::pair<IntegerValue, IntegerValue> bounding_box_size,
566 int brute_force_threshold) {
567 const int num_items_originally =
568 result.items_participating_on_conflict_.size();
569 if (num_items_originally > 2 * brute_force_threshold) {
570 // Don't even try on problems too big.
571 return false;
572 }
573 std::vector<IntegerValue> sizes_x;
574 std::vector<IntegerValue> sizes_y;
575 std::vector<int> indexes;
576 std::vector<bool> to_be_removed(num_items_originally, false);
577
578 sizes_x.reserve(num_items_originally - 1);
579 sizes_y.reserve(num_items_originally - 1);
580 for (int i = 0; i < num_items_originally; i++) {
581 sizes_x.clear();
582 sizes_y.clear();
583 // Look for a conflict using all non-removed items but the i-th one.
584 for (int j = 0; j < num_items_originally; j++) {
585 if (i == j || to_be_removed[j]) {
586 continue;
587 }
588 sizes_x.push_back(result.items_participating_on_conflict_[j].size_x);
589 sizes_y.push_back(result.items_participating_on_conflict_[j].size_y);
590 }
592 sizes_x, sizes_y, bounding_box_size, brute_force_threshold);
594 // We still have a conflict if we remove the i-th item!
595 to_be_removed[i] = true;
596 }
597 }
598 if (!std::any_of(to_be_removed.begin(), to_be_removed.end(),
599 [](bool b) { return b; })) {
600 return false;
601 }
602 OrthogonalPackingResult original = result;
603 result.slack_ = 0;
604 result.conflict_type_ = OrthogonalPackingResult::ConflictType::BRUTE_FORCE;
606 result.items_participating_on_conflict_.clear();
607 for (int i = 0; i < num_items_originally; i++) {
608 if (to_be_removed[i]) {
609 continue;
610 }
611 result.items_participating_on_conflict_.push_back(
612 original.items_participating_on_conflict_[i]);
613 }
614 return true;
615}
616
618OrthogonalPackingInfeasibilityDetector::TestFeasibilityImpl(
619 absl::Span<const IntegerValue> sizes_x,
620 absl::Span<const IntegerValue> sizes_y,
621 std::pair<IntegerValue, IntegerValue> bounding_box_size,
622 const OrthogonalPackingOptions& options) {
623 using ConflictType = OrthogonalPackingResult::ConflictType;
624
625 const int num_items = sizes_x.size();
626 DCHECK_EQ(num_items, sizes_y.size());
627 const IntegerValue bb_area =
628 bounding_box_size.first * bounding_box_size.second;
629 IntegerValue total_energy = 0;
630
631 auto make_item = [sizes_x, sizes_y](int i) {
632 return OrthogonalPackingResult::Item{
633 .index = i, .size_x = sizes_x[i], .size_y = sizes_y[i]};
634 };
635
636 index_by_decreasing_x_size_.resize(num_items);
637 index_by_decreasing_y_size_.resize(num_items);
638 for (int i = 0; i < num_items; i++) {
639 total_energy += sizes_x[i] * sizes_y[i];
640 index_by_decreasing_x_size_[i] = i;
641 index_by_decreasing_y_size_[i] = i;
642 if (sizes_x[i] > bounding_box_size.first ||
643 sizes_y[i] > bounding_box_size.second) {
644 OrthogonalPackingResult result(
646 result.conflict_type_ = ConflictType::TRIVIAL;
647 result.items_participating_on_conflict_ = {make_item(i)};
648 return result;
649 }
650 }
651
652 if (num_items <= 1) {
653 return OrthogonalPackingResult(OrthogonalPackingResult::Status::FEASIBLE);
654 }
655
656 std::sort(index_by_decreasing_x_size_.begin(),
657 index_by_decreasing_x_size_.end(),
658 [&sizes_x, &sizes_y](int a, int b) {
659 // Break ties with y-size
660 return std::tie(sizes_x[a], sizes_y[a]) >
661 std::tie(sizes_x[b], sizes_y[b]);
662 });
663 std::sort(index_by_decreasing_y_size_.begin(),
664 index_by_decreasing_y_size_.end(),
665 [&sizes_y, &sizes_x](int a, int b) {
666 return std::tie(sizes_y[a], sizes_x[a]) >
667 std::tie(sizes_y[b], sizes_x[b]);
668 });
669
670 // First look for pairwise incompatible pairs.
671 if (options.use_pairwise) {
672 if (auto pair = FindPairwiseConflict(sizes_x, sizes_y, bounding_box_size,
673 index_by_decreasing_x_size_,
674 index_by_decreasing_y_size_);
675 pair.has_value()) {
676 OrthogonalPackingResult result(
678 result.conflict_type_ = ConflictType::PAIRWISE;
679 result.items_participating_on_conflict_ = {
680 make_item(pair.value().first), make_item(pair.value().second)};
681 return result;
682 }
683 if (num_items == 2) {
684 return OrthogonalPackingResult(OrthogonalPackingResult::Status::FEASIBLE);
685 }
686 }
687
688 OrthogonalPackingResult result(OrthogonalPackingResult::Status::UNKNOWN);
689 if (total_energy > bb_area) {
690 result.conflict_type_ = ConflictType::TRIVIAL;
692 std::vector<std::pair<int, IntegerValue>> index_to_energy;
693 index_to_energy.reserve(num_items);
694 for (int i = 0; i < num_items; i++) {
695 index_to_energy.push_back({i, sizes_x[i] * sizes_y[i]});
696 }
697 std::sort(index_to_energy.begin(), index_to_energy.end(),
698 [](const std::pair<int, IntegerValue>& a,
699 const std::pair<int, IntegerValue>& b) {
700 return a.second > b.second;
701 });
702 IntegerValue recomputed_energy = 0;
703 for (int i = 0; i < index_to_energy.size(); i++) {
704 recomputed_energy += index_to_energy[i].second;
705 if (recomputed_energy > bb_area) {
706 result.items_participating_on_conflict_.resize(i + 1);
707 for (int j = 0; j <= i; j++) {
708 result.items_participating_on_conflict_[j] =
709 make_item(index_to_energy[j].first);
710 }
711 result.slack_ = recomputed_energy - bb_area - 1;
712 break;
713 }
714 }
715 }
716
717 const int minimum_conflict_size = options.use_pairwise ? 3 : 2;
718 if (result.items_participating_on_conflict_.size() == minimum_conflict_size) {
719 return result;
720 }
721
722 if (options.use_dff_f0) {
723 // If there is no pairwise incompatible pairs, this DFF cannot find a
724 // conflict by enlarging a item on both x and y directions: this would
725 // create an item as long as the whole box and another item as high as the
726 // whole box, which is obviously incompatible, and this incompatibility
727 // would be present already before enlarging the items since it is a DFF. So
728 // it is enough to test making items wide or high, but no need to try both.
729 IntegerValue best_k;
730 auto conflict =
731 GetDffConflict(sizes_x, sizes_y, index_by_decreasing_x_size_, sizes_x,
732 bounding_box_size.first, bounding_box_size.first,
733 total_energy, bb_area, &best_k);
734 if (conflict.IsBetterThan(result)) {
735 result = conflict;
736 }
737
738 conflict =
739 GetDffConflict(sizes_y, sizes_x, index_by_decreasing_y_size_, sizes_y,
740 bounding_box_size.second, bounding_box_size.second,
741 total_energy, bb_area, &best_k);
742 for (auto& item : conflict.items_participating_on_conflict_) {
743 std::swap(item.size_x, item.size_y);
744 }
745 if (conflict.IsBetterThan(result)) {
746 result = conflict;
747 }
748 }
749
750 if (result.items_participating_on_conflict_.size() == minimum_conflict_size) {
751 return result;
752 }
753
754 bool found_scheduling_solution = false;
755 if (options.use_dff_f2) {
756 // Checking for conflicts using f_2 is expensive, so first try a quick
757 // algorithm to check if there is no conflict to be found. See the comments
758 // on top of FindHeuristicSchedulingSolution().
759 if (FindHeuristicSchedulingSolution(
760 sizes_x, sizes_y, index_by_decreasing_x_size_,
761 bounding_box_size.first, bounding_box_size.second,
762 scheduling_profile_, new_scheduling_profile_) ||
763 FindHeuristicSchedulingSolution(
764 sizes_y, sizes_x, index_by_decreasing_y_size_,
765 bounding_box_size.second, bounding_box_size.first,
766 scheduling_profile_, new_scheduling_profile_)) {
767 num_scheduling_possible_++;
768 CHECK(result.result_ != OrthogonalPackingResult::Status::INFEASIBLE);
769 found_scheduling_solution = true;
770 }
771 }
772
773 if (!found_scheduling_solution && options.use_dff_f2) {
774 // We only check for conflicts applying this DFF on heights and widths, but
775 // not on both, which would be too expensive if done naively.
776 auto conflict = CheckFeasibilityWithDualFunction2(
777 sizes_x, sizes_y, index_by_decreasing_x_size_, bounding_box_size.first,
778 bounding_box_size.second,
779 options.dff2_max_number_of_parameters_to_check);
780 if (conflict.IsBetterThan(result)) {
781 result = conflict;
782 }
783
784 if (result.items_participating_on_conflict_.size() ==
785 minimum_conflict_size) {
786 return result;
787 }
788 conflict = CheckFeasibilityWithDualFunction2(
789 sizes_y, sizes_x, index_by_decreasing_y_size_, bounding_box_size.second,
790 bounding_box_size.first,
791 options.dff2_max_number_of_parameters_to_check);
792 for (auto& item : conflict.items_participating_on_conflict_) {
793 std::swap(item.size_x, item.size_y);
794 }
795 if (conflict.IsBetterThan(result)) {
796 result = conflict;
797 }
798 }
799
800 if (result.result_ == OrthogonalPackingResult::Status::UNKNOWN) {
802 sizes_x, sizes_y, bounding_box_size, options.brute_force_threshold);
803 num_brute_force_calls_ +=
806 result.conflict_type_ = ConflictType::BRUTE_FORCE;
808 result.items_participating_on_conflict_.resize(num_items);
809 for (int i = 0; i < num_items; i++) {
810 result.items_participating_on_conflict_[i] = make_item(i);
811 }
814 }
815 }
816
817 if (result.result_ == OrthogonalPackingResult::Status::INFEASIBLE) {
818 num_brute_force_relaxation_ += RelaxConflictWithBruteForce(
819 result, bounding_box_size, options.brute_force_threshold);
820 }
821
822 return result;
823}
824
826 absl::Span<const IntegerValue> sizes_x,
827 absl::Span<const IntegerValue> sizes_y,
828 std::pair<IntegerValue, IntegerValue> bounding_box_size,
829 const OrthogonalPackingOptions& options) {
830 using ConflictType = OrthogonalPackingResult::ConflictType;
831
832 num_calls_++;
834 TestFeasibilityImpl(sizes_x, sizes_y, bounding_box_size, options);
835
836 if (result.result_ == OrthogonalPackingResult::Status::INFEASIBLE) {
837 num_conflicts_++;
838 switch (result.conflict_type_) {
839 case ConflictType::DFF_F0:
840 num_conflicts_dff0_++;
841 break;
842 case ConflictType::DFF_F2:
843 num_conflicts_dff2_++;
844 break;
845 case ConflictType::PAIRWISE:
846 num_conflicts_two_items_++;
847 break;
848 case ConflictType::TRIVIAL:
849 // The total area of the items was larger than the area of the box.
850 num_trivial_conflicts_++;
851 break;
852 case ConflictType::BRUTE_FORCE:
853 num_brute_force_conflicts_++;
854 break;
855 case ConflictType::NO_CONFLICT:
856 LOG(FATAL) << "Should never happen";
857 break;
858 }
859 }
860 return result;
861}
862
864 int i, Coord coord, IntegerValue lower_bound) {
865 Item& item = items_participating_on_conflict_[i];
866 IntegerValue& size = coord == Coord::kCoordX ? item.size_x : item.size_y;
867 const IntegerValue orthogonal_size =
868 coord == Coord::kCoordX ? item.size_y : item.size_x;
869
870 if (size <= lower_bound || orthogonal_size > slack_) {
871 return false;
872 }
873 const IntegerValue new_size =
874 std::max(lower_bound, size - slack_ / orthogonal_size);
875 slack_ -= (size - new_size) * orthogonal_size;
876 DCHECK_NE(size, new_size);
877 DCHECK_GE(slack_, 0);
878 size = new_size;
879 return true;
880}
881
882} // namespace sat
883} // namespace operations_research
OrthogonalPackingResult TestFeasibility(absl::Span< const IntegerValue > sizes_x, absl::Span< const IntegerValue > sizes_y, std::pair< IntegerValue, IntegerValue > bounding_box_size, const OrthogonalPackingOptions &options=OrthogonalPackingOptions())
bool TryUseSlackToReduceItemSize(int i, Coord coord, IntegerValue lower_bound=0)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
int64_t FloorSquareRoot(int64_t a)
The argument must be non-negative.
Definition util.cc:300
BruteForceResult BruteForceOrthogonalPacking(absl::Span< const IntegerValue > sizes_x, absl::Span< const IntegerValue > sizes_y, std::pair< IntegerValue, IntegerValue > bounding_box_size, int max_complexity)
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue.value())
In SWIG mode, we don't want anything besides these top-level includes.
Select next search node to expand Select next item_i to add this new search node to the search Generate a new search node where item_i is not in the knapsack Check validity of this new partial solution(using propagators) - If valid