Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
diffn_util.h
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
14#ifndef OR_TOOLS_SAT_DIFFN_UTIL_H_
15#define OR_TOOLS_SAT_DIFFN_UTIL_H_
16
17#include <algorithm>
18#include <cmath>
19#include <cstdlib>
20#include <limits>
21#include <optional>
22#include <string>
23#include <string_view>
24#include <tuple>
25#include <utility>
26#include <vector>
27
28#include "absl/container/flat_hash_set.h"
29#include "absl/container/inlined_vector.h"
30#include "absl/log/check.h"
31#include "absl/random/bit_gen_ref.h"
32#include "absl/strings/str_format.h"
33#include "absl/types/optional.h"
34#include "absl/types/span.h"
37#include "ortools/sat/util.h"
40
41namespace operations_research {
42namespace sat {
43
44struct Rectangle {
45 IntegerValue x_min;
46 IntegerValue x_max;
47 IntegerValue y_min;
48 IntegerValue y_max;
49
50 void GrowToInclude(const Rectangle& other) {
51 x_min = std::min(x_min, other.x_min);
52 y_min = std::min(y_min, other.y_min);
53 x_max = std::max(x_max, other.x_max);
54 y_max = std::max(y_max, other.y_max);
55 }
56
57 IntegerValue Area() const { return SizeX() * SizeY(); }
58
59 IntegerValue CapArea() const {
61 }
62
63 IntegerValue SizeX() const { return x_max - x_min; }
64 IntegerValue SizeY() const { return y_max - y_min; }
65
66 bool IsDisjoint(const Rectangle& other) const;
67
68 // The methods below are not meant to be used with zero-area rectangles.
69
70 // Returns an empty rectangle if no intersection.
71 Rectangle Intersect(const Rectangle& other) const;
72 IntegerValue IntersectArea(const Rectangle& other) const;
73
74 bool IsInsideOf(const Rectangle& other) const {
75 return x_min >= other.x_min && x_max <= other.x_max &&
76 y_min >= other.y_min && y_max <= other.y_max;
77 }
78
79 // Returns `this \ other` as a set of disjoint rectangles of non-empty area.
80 // The resulting vector will have at most four elements.
81 absl::InlinedVector<Rectangle, 4> RegionDifference(
82 const Rectangle& other) const;
83
84 template <typename Sink>
85 friend void AbslStringify(Sink& sink, const Rectangle& r) {
86 absl::Format(&sink, "rectangle(x(%i..%i), y(%i..%i))", r.x_min.value(),
87 r.x_max.value(), r.y_min.value(), r.y_max.value());
88 }
89
90 bool operator==(const Rectangle& other) const {
91 return std::tie(x_min, x_max, y_min, y_max) ==
92 std::tie(other.x_min, other.x_max, other.y_min, other.y_max);
93 }
94
95 bool operator!=(const Rectangle& other) const { return !(other == *this); }
96
98 return Rectangle{.x_min = IntegerValue(0),
99 .x_max = IntegerValue(0),
100 .y_min = IntegerValue(0),
101 .y_max = IntegerValue(0)};
102 }
103};
104
105inline Rectangle Rectangle::Intersect(const Rectangle& other) const {
106 const IntegerValue ret_x_min = std::max(x_min, other.x_min);
107 const IntegerValue ret_y_min = std::max(y_min, other.y_min);
108 const IntegerValue ret_x_max = std::min(x_max, other.x_max);
109 const IntegerValue ret_y_max = std::min(y_max, other.y_max);
110
111 if (ret_x_min >= ret_x_max || ret_y_min >= ret_y_max) {
112 return GetEmpty();
113 } else {
114 return Rectangle{.x_min = ret_x_min,
115 .x_max = ret_x_max,
116 .y_min = ret_y_min,
117 .y_max = ret_y_max};
118 }
119}
120
121inline IntegerValue Rectangle::IntersectArea(const Rectangle& other) const {
122 const IntegerValue ret_x_min = std::max(x_min, other.x_min);
123 const IntegerValue ret_y_min = std::max(y_min, other.y_min);
124 const IntegerValue ret_x_max = std::min(x_max, other.x_max);
125 const IntegerValue ret_y_max = std::min(y_max, other.y_max);
126
127 if (ret_x_min >= ret_x_max || ret_y_min >= ret_y_max) {
128 return 0;
129 } else {
130 return (ret_x_max - ret_x_min) * (ret_y_max - ret_y_min);
131 }
132}
133
134// Returns the L2 distance between the centers of the two rectangles.
135inline double CenterToCenterL2Distance(const Rectangle& a, const Rectangle& b) {
136 const double diff_x =
137 (static_cast<double>(a.x_min.value()) + a.x_max.value()) / 2.0 -
138 (static_cast<double>(b.x_min.value()) + b.x_max.value()) / 2.0;
139 const double diff_y =
140 (static_cast<double>(a.y_min.value()) + a.y_max.value()) / 2.0 -
141 (static_cast<double>(b.y_min.value()) + b.y_max.value()) / 2.0;
142 return std::sqrt(diff_x * diff_x + diff_y * diff_y);
143}
144
146 const Rectangle& b) {
147 const double diff_x =
148 (static_cast<double>(a.x_min.value()) + a.x_max.value()) / 2.0 -
149 (static_cast<double>(b.x_min.value()) + b.x_max.value()) / 2.0;
150 const double diff_y =
151 (static_cast<double>(a.y_min.value()) + a.y_max.value()) / 2.0 -
152 (static_cast<double>(b.y_min.value()) + b.y_max.value()) / 2.0;
153 return std::max(std::abs(diff_x), std::abs(diff_y));
154}
155
156// Creates a graph when two nodes are connected iff their rectangles overlap.
157// Then partition into connected components.
158CompactVectorVector<int> GetOverlappingRectangleComponents(
159 absl::Span<const Rectangle> rectangles);
160
161// Visible for testing. The algo is in O(n^4) so shouldn't be used directly.
162// Returns true if there exist a bounding box with too much energy.
163bool BoxesAreInEnergyConflict(absl::Span<const Rectangle> rectangles,
164 absl::Span<const IntegerValue> energies,
165 absl::Span<const int> boxes,
166 Rectangle* conflict = nullptr);
167
168// Checks that there is indeed a conflict for the given bounding_box and
169// report it. This returns false for convenience as we usually want to return
170// false on a conflict.
171//
172// TODO(user): relax the bounding box dimension to have a relaxed explanation.
173// We can also minimize the number of required intervals.
174bool ReportEnergyConflict(Rectangle bounding_box, absl::Span<const int> boxes,
175 SchedulingConstraintHelper* x,
176 SchedulingConstraintHelper* y);
177
178// A O(n^2) algorithm to analyze all the relevant X intervals and infer a
179// threshold of the y size of a bounding box after which there is no point
180// checking for energy overload.
181//
182// Returns false on conflict, and fill the bounding box that caused the
183// conflict.
184//
185// If transpose is true, we analyze the relevant Y intervals instead.
186bool AnalyzeIntervals(bool transpose, absl::Span<const int> boxes,
187 absl::Span<const Rectangle> rectangles,
188 absl::Span<const IntegerValue> rectangle_energies,
189 IntegerValue* x_threshold, IntegerValue* y_threshold,
190 Rectangle* conflict = nullptr);
191
192// Removes boxes with a size above the thresholds. Also randomize the order.
193// Because we rely on various heuristic, this allow to change the order from
194// one call to the next.
195absl::Span<int> FilterBoxesAndRandomize(
196 absl::Span<const Rectangle> cached_rectangles, absl::Span<int> boxes,
197 IntegerValue threshold_x, IntegerValue threshold_y, absl::BitGenRef random);
198
199// Given the total energy of all rectangles (sum of energies[box]) we know that
200// any box with an area greater than that cannot participate in any "bounding
201// box" conflict. As we remove this box, the total energy decrease, so we might
202// remove more. This works in O(n log n).
203absl::Span<int> FilterBoxesThatAreTooLarge(
204 absl::Span<const Rectangle> cached_rectangles,
205 absl::Span<const IntegerValue> energies, absl::Span<int> boxes);
206
208 int index;
209 IntegerValue start;
210 IntegerValue end;
211
212 bool operator==(const IndexedInterval& rhs) const {
213 return std::tie(start, end, index) ==
214 std::tie(rhs.start, rhs.end, rhs.index);
215 }
216
217 // NOTE(user): We would like to use TUPLE_DEFINE_STRUCT, but sadly it doesn't
218 // support //buildenv/target:non_prod.
220 bool operator()(const IndexedInterval& a, const IndexedInterval& b) const {
221 return std::tie(a.start, a.end, a.index) <
222 std::tie(b.start, b.end, b.index);
223 }
224 };
226 bool operator()(const IndexedInterval& a, const IndexedInterval& b) const {
227 return a.start < b.start;
228 }
229 };
230
231 template <typename Sink>
232 friend void AbslStringify(Sink& sink, const IndexedInterval& interval) {
233 absl::Format(&sink, "[%v..%v] (#%v)", interval.start, interval.end,
234 interval.index);
235 }
236};
237
238// Given n fixed intervals that must be sorted by
239// IndexedInterval::ComparatorByStart(), returns the subsets of intervals that
240// overlap during at least one time unit. Note that we only return "maximal"
241// subset and filter subset strictly included in another.
242//
243// IMPORTANT: The span of intervals will not be usable after this function! this
244// could be changed if needed with an extra copy.
245//
246// All Intervals must have a positive size.
247//
248// The algo is in O(n log n) + O(result_size) which is usually O(n^2).
249//
250// If the last argument is not empty, we will sort the interval in the result
251// according to the given order, i.e. i will be before j if order[i] < order[j].
252void ConstructOverlappingSets(absl::Span<IndexedInterval> intervals,
253 CompactVectorVector<int>* result,
254 absl::Span<const int> order = {});
255
256// Given n intervals, returns the set of connected components (using the overlap
257// relation between 2 intervals). Components are sorted by their start, and
258// inside a component, the intervals are also sorted by start.
259// `intervals` is only sorted (by start), and not modified otherwise.
261 std::vector<IndexedInterval>* intervals,
262 std::vector<std::vector<int>>* components);
263
264// Similar to GetOverlappingIntervalComponents(), but returns the indices of
265// all intervals whose removal would create one more connected component in the
266// interval graph. Those are sorted by start. See:
267// https://en.wikipedia.org/wiki/Glossary_of_graph_theory#articulation_point.
268std::vector<int> GetIntervalArticulationPoints(
269 std::vector<IndexedInterval>* intervals);
270
272 int index;
273 struct Interval {
274 IntegerValue start_min;
275 IntegerValue start_max;
276 IntegerValue end_min;
277 IntegerValue end_max;
278 };
281
282 template <typename Sink>
283 friend void AbslStringify(Sink& sink, const ItemWithVariableSize& item) {
284 absl::Format(&sink, "Item %v: [(%v..%v)-(%v..%v)] x [(%v..%v)-(%v..%v)]",
285 item.index, item.x.start_min, item.x.start_max, item.x.end_min,
286 item.x.end_max, item.y.start_min, item.y.start_max,
287 item.y.end_min, item.y.end_max);
288 }
289};
290
309
310// Find pair of items that are either in conflict or could have their range
311// shrinked to avoid conflict.
312void AppendPairwiseRestrictions(absl::Span<const ItemWithVariableSize> items,
313 std::vector<PairwiseRestriction>* result);
314
315// Same as above, but test `items` against `other_items` and append the
316// restrictions found to `result`.
318 absl::Span<const ItemWithVariableSize> items,
319 absl::Span<const ItemWithVariableSize> other_items,
320 std::vector<PairwiseRestriction>* result);
321
322// This class is used by the no_overlap_2d constraint to maintain the envelope
323// of a set of rectangles. This envelope is not the convex hull, but the exact
324// polyline (aligned with the x and y axis) that contains all the rectangles
325// passed with the AddRectangle() call.
327 public:
328 // Simple start of a rectangle. This is used to represent the residual
329 // capacity profile.
330 struct Rectangle {
331 Rectangle(IntegerValue start, IntegerValue height)
332 : start(start), height(height) {}
333
334 bool operator<(const Rectangle& other) const { return start < other.start; }
335 bool operator==(const Rectangle& other) const {
336 return start == other.start && height == other.height;
337 }
338
339 IntegerValue start = IntegerValue(0);
340 IntegerValue height = IntegerValue(0);
341 };
342
343 void Clear();
344
345 // Adds a rectangle to the current shape.
346 void AddRectangle(IntegerValue x_min, IntegerValue x_max, IntegerValue y_min,
347 IntegerValue y_max);
348
349 // Adds a mandatory profile consumption. All mandatory usages will be
350 // subtracted from the y_max-y_min profile to build the residual capacity.
351 void AddMandatoryConsumption(IntegerValue x_min, IntegerValue x_max,
352 IntegerValue y_height);
353
354 // Returns the profile of the function:
355 // capacity(x) = max(y_max of rectangles overlapping x) - min(y_min of
356 // rectangle overlapping x) - sum(y_height of mandatory rectangles
357 // overlapping x) where a rectangle overlaps x if x_min <= x < x_max.
358 //
359 // Note the profile can contain negative heights in case the mandatory part
360 // exceeds the range on the y axis.
361 //
362 // Note that it adds a sentinel (kMinIntegerValue, 0) at the start. It is
363 // useful when we reverse the direction on the x axis.
364 void BuildResidualCapacityProfile(std::vector<Rectangle>* result);
365
366 // Returns the exact area of the bounding polyline of all rectangles added.
367 //
368 // Note that this will redo the computation each time.
369 IntegerValue GetBoundingArea();
370
371 private:
372 // Type for the capacity events.
373 enum EventType { START_RECTANGLE, END_RECTANGLE, CHANGE_MANDATORY_PROFILE };
374
375 // Individual events.
376 struct Event {
377 IntegerValue time;
378 IntegerValue y_min;
379 IntegerValue y_max;
380 EventType type;
381 int index;
382
383 bool operator<(const Event& other) const { return time < other.time; }
384 };
385
386 // Element of the integer_pq heap.
387 struct QueueElement {
388 int Index() const { return index; }
389 bool operator<(const QueueElement& o) const { return value < o.value; }
390
391 int index;
392 IntegerValue value;
393 };
394
395 static Event StartRectangleEvent(int index, IntegerValue x_min,
396 IntegerValue y_min, IntegerValue y_max) {
397 return {x_min, y_min, y_max, START_RECTANGLE, index};
398 }
399
400 static Event EndRectangleEvent(int index, IntegerValue x_max) {
401 return {x_max, kMinIntegerValue, kMinIntegerValue, END_RECTANGLE, index};
402 }
403
404 static Event ChangeMandatoryProfileEvent(IntegerValue x, IntegerValue delta) {
405 return {x, /*y_min=*/delta, /*y_max=*/kMinIntegerValue,
406 CHANGE_MANDATORY_PROFILE, /*index=*/-1};
407 }
408
409 std::vector<Event> events_;
410 int num_rectangles_added_ = 0;
411};
412
413// 1D counterpart of RectangleInRange::GetMinimumIntersectionArea.
414// Finds the minimum possible overlap of a interval of size `size` that fits in
415// [range_min, range_max] and a second interval [interval_min, interval_max].
416IntegerValue Smallest1DIntersection(IntegerValue range_min,
417 IntegerValue range_max, IntegerValue size,
418 IntegerValue interval_min,
419 IntegerValue interval_max);
420
421// A rectangle of size (`x_size`, `y_size`) that can freely move inside the
422// `bounding_area` rectangle.
426 IntegerValue x_size;
427 IntegerValue y_size;
428
435
436 bool operator==(const RectangleInRange& other) const {
437 return box_index == other.box_index &&
438 bounding_area == other.bounding_area && x_size == other.x_size &&
439 y_size == other.y_size;
440 }
441
442 // Returns the position of the rectangle fixed to one of the corner of its
443 // range.
445 switch (p) {
447 return Rectangle{.x_min = bounding_area.x_min,
448 .x_max = bounding_area.x_min + x_size,
449 .y_min = bounding_area.y_min,
450 .y_max = bounding_area.y_min + y_size};
451 case Corner::TOP_LEFT:
452 return Rectangle{.x_min = bounding_area.x_min,
453 .x_max = bounding_area.x_min + x_size,
454 .y_min = bounding_area.y_max - y_size,
455 .y_max = bounding_area.y_max};
457 return Rectangle{.x_min = bounding_area.x_max - x_size,
458 .x_max = bounding_area.x_max,
459 .y_min = bounding_area.y_min,
460 .y_max = bounding_area.y_min + y_size};
462 return Rectangle{.x_min = bounding_area.x_max - x_size,
463 .x_max = bounding_area.x_max,
464 .y_min = bounding_area.y_max - y_size,
465 .y_max = bounding_area.y_max};
466 }
467 }
468
470
471 // Returns an empty rectangle if it is possible for no intersection to happen.
472 Rectangle GetMinimumIntersection(const Rectangle& containing_area) const {
473 IntegerValue smallest_area = std::numeric_limits<IntegerValue>::max();
474 Rectangle best_intersection;
475 for (int corner_idx = 0; corner_idx < 4; ++corner_idx) {
476 const Corner p = static_cast<Corner>(corner_idx);
477 Rectangle intersection = containing_area.Intersect(GetAtCorner(p));
478 const IntegerValue intersection_area = intersection.Area();
479 if (intersection_area == 0) {
480 return Rectangle::GetEmpty();
481 }
482 if (intersection_area < smallest_area) {
483 smallest_area = intersection_area;
484 best_intersection = std::move(intersection);
485 }
486 }
487 return best_intersection;
488 }
489
491 const Rectangle& containing_area) const {
493 x_size, containing_area.x_min,
494 containing_area.x_max) *
496 y_size, containing_area.y_min,
497 containing_area.y_max);
498 }
499
501 // Weird math to avoid overflow.
502 if (bounding_area.SizeX() - x_size >= x_size ||
503 bounding_area.SizeY() - y_size >= y_size) {
504 return Rectangle::GetEmpty();
505 }
506 return Rectangle{.x_min = bounding_area.x_max - x_size,
507 .x_max = bounding_area.x_min + x_size,
508 .y_min = bounding_area.y_max - y_size,
509 .y_max = bounding_area.y_min + y_size};
510 }
511
513 const Rectangle& containing_area, const RectangleInRange& original,
514 const IntegerValue& min_intersect_x,
515 const IntegerValue& min_intersect_y) {
516 const IntegerValue x_size = original.x_size;
517 const IntegerValue y_size = original.y_size;
518
519 RectangleInRange result;
520 result.x_size = x_size;
521 result.y_size = y_size;
522 result.box_index = original.box_index;
523
524 // We cannot intersect more units than the whole item.
525 DCHECK_GE(x_size, min_intersect_x);
526 DCHECK_GE(y_size, min_intersect_y);
527
528 // Units that can *not* intersect per dimension.
529 const IntegerValue x_headroom = x_size - min_intersect_x;
530 const IntegerValue y_headroom = y_size - min_intersect_y;
531
532 result.bounding_area.x_min = containing_area.x_min - x_headroom;
533 result.bounding_area.x_max = containing_area.x_max + x_headroom;
534 result.bounding_area.y_min = containing_area.y_min - y_headroom;
535 result.bounding_area.y_max = containing_area.y_max + y_headroom;
536
537 return result;
538 }
539
540 template <typename Sink>
541 friend void AbslStringify(Sink& sink, const RectangleInRange& r) {
542 absl::Format(&sink, "item(size=%vx%v, BB=%v)", r.x_size, r.y_size,
543 r.bounding_area);
544 }
545};
546
547// Cheaply test several increasingly smaller rectangles for energy conflict.
548// More precisely, each call to `Shrink()` cost O(k + n) operations, where k is
549// the number of points that shrinking the probing rectangle will cross and n is
550// the number of items which are in a range that overlaps the probing rectangle
551// in both sides in the dimension that is getting shrinked. When calling
552// repeatedely `Shrink()` until the probing rectangle collapse into a single
553// point, the O(k) component adds up to a O(M) cost, where M is the number of
554// items. This means this procedure is linear in time if the ranges of the items
555// are small.
556//
557// The energy is defined as the minimum occupied area inside the probing
558// rectangle. For more details, see Clautiaux, François, et al. "A new
559// constraint programming approach for the orthogonal packing problem."
560// Computers & Operations Research 35.3 (2008): 944-959.
561//
562// This is used by FindRectanglesWithEnergyConflictMC() below.
564 public:
565 // It will initialize with the bounding box of the whole set.
566 explicit ProbingRectangle(const std::vector<RectangleInRange>& intervals);
567
568 enum Edge { TOP = 0, LEFT = 1, BOTTOM = 2, RIGHT = 3 };
569
570 // Reset to the bounding box of the whole set.
571 void Reset();
572
573 // Shrink the rectangle by moving one of its four edges to the next
574 // "interesting" value. The interesting values for x or y are the ones that
575 // correspond to a boundary, ie., a value that corresponds to one of {min,
576 // min + size, max - size, max} of a rectangle.
577 void Shrink(Edge edge);
578
579 bool CanShrink(Edge edge) const;
580
581 bool IsMinimal() const {
582 // We only need to know if there is slack on both dimensions. Actually
583 // CanShrink(BOTTOM) == CanShrink(TOP) and conversely.
585 }
586
587 // Test-only method that check that all internal incremental counts are
588 // correct by comparing with recalculating them from scratch.
589 void ValidateInvariants() const;
590
591 // How much of GetMinimumEnergy() will change if Shrink() is called.
592 IntegerValue GetShrinkDeltaEnergy(Edge edge) const {
593 return cached_delta_energy_[edge];
594 }
595
596 // How much of GetCurrentRectangleArea() will change if Shrink() is called.
597 IntegerValue GetShrinkDeltaArea(Edge edge) const;
598
600 IntegerValue GetCurrentRectangleArea() const { return probe_area_; }
601
602 // This is equivalent of, for every item:
603 // - Call GetMinimumIntersectionArea() with GetCurrentRectangle().
604 // - Return the total sum of the areas.
605 IntegerValue GetMinimumEnergy() const { return minimum_energy_; }
606
607 const std::vector<RectangleInRange>& Intervals() const { return intervals_; }
608
613
614 private:
615 void CacheShrinkDeltaEnergy(int dimension);
616
617 template <Edge edge>
618 void ShrinkImpl();
619
620 struct IntervalPoint {
621 IntegerValue value;
622 int index;
623 };
624
625 std::vector<IntervalPoint> interval_points_sorted_by_x_;
626 std::vector<IntervalPoint> interval_points_sorted_by_y_;
627
628 // Those two vectors are not strictly needed, we could instead iterate
629 // directly on the two vectors above, but the code would be much uglier.
630 struct PointsForCoordinate {
631 IntegerValue coordinate;
632 absl::Span<IntervalPoint> items_touching_coordinate;
633 };
634 std::vector<PointsForCoordinate> grouped_intervals_sorted_by_x_;
635 std::vector<PointsForCoordinate> grouped_intervals_sorted_by_y_;
636
637 const std::vector<RectangleInRange>& intervals_;
638
639 IntegerValue full_energy_;
640 IntegerValue minimum_energy_;
641 IntegerValue probe_area_;
642 int indexes_[4];
643 int next_indexes_[4];
644
645 absl::flat_hash_set<int> ranges_touching_both_boundaries_[2];
646 IntegerValue corner_count_[4] = {0, 0, 0, 0};
647 IntegerValue intersect_length_[4] = {0, 0, 0, 0};
648 IntegerValue cached_delta_energy_[4];
649};
650
651// Monte-Carlo inspired heuristic to find a rectangles with an energy conflict:
652// - start with a rectangle equals to the full bounding box of the elements;
653// - shrink the rectangle by an edge to the next "interesting" value. Choose
654// the edge randomly, but biased towards the change that increases the ratio
655// area_inside / area_rectangle;
656// - collect a result at every conflict or every time the ratio
657// used_energy/available_energy is more than `candidate_energy_usage_factor`;
658// - stop when the rectangle is empty.
660 // Known conflicts: the minimal energy used inside the rectangle is larger
661 // than the area of the rectangle.
662 std::vector<Rectangle> conflicts;
663 // Rectangles without a conflict but having used_energy/available_energy >
664 // candidate_energy_usage_factor. Those are good candidates for finding
665 // conflicts using more sophisticated heuristics. Those rectangles are
666 // ordered so the n-th rectangle is always fully inside the n-1-th one.
667 std::vector<Rectangle> candidates;
668};
670 const std::vector<RectangleInRange>& intervals, absl::BitGenRef random,
671 double temperature, double candidate_energy_usage_factor);
672
673// Render a packing solution as a Graphviz dot file. Only works in the "neato"
674// or "fdp" Graphviz backends.
675std::string RenderDot(std::optional<Rectangle> bb,
676 absl::Span<const Rectangle> solution,
677 std::string_view extra_dot_payload = "");
678
679// Given a bounding box and a list of rectangles inside that bounding box,
680// returns a list of rectangles partitioning the empty area inside the bounding
681// box.
682std::vector<Rectangle> FindEmptySpaces(
683 const Rectangle& bounding_box, std::vector<Rectangle> ocupied_rectangles);
684
685// Given two regions, each one of them defined by a vector of non-overlapping
686// rectangles paving them, returns a vector of non-overlapping rectangles that
687// paves the points that were part of the first region but not of the second.
688// This can also be seen as the set difference of the points of the regions.
689std::vector<Rectangle> PavedRegionDifference(
690 std::vector<Rectangle> original_region,
691 absl::Span<const Rectangle> area_to_remove);
692
693// The two regions must be defined by non-overlapping rectangles.
694inline bool RegionIncludesOther(absl::Span<const Rectangle> region,
695 absl::Span<const Rectangle> other) {
696 return PavedRegionDifference({other.begin(), other.end()}, region).empty();
697}
698
699// For a given a set of N rectangles in `rectangles`, there might be up to
700// N*(N-1)/2 pairs of rectangles that intersect one another. If each of these
701// pairs describe an arc and each rectangle describe a node, the rectangles and
702// their intersections describe a graph. This function returns the full spanning
703// forest for this graph (ie., a spanning tree for each connected component).
704// This function allows to know if a set of rectangles has any intersection,
705// find an example intersection for each rectangle that has one, or split the
706// rectangles into connected components according to their intersections.
707//
708// The returned tuples are the arcs of the spanning forest represented by their
709// indices in the input vector.
710//
711// This function works with degenerate rectangles (ie., points or lines) and
712// have the same semantics for overlap as Rectangle::IsDisjoint().
713//
714// Note: This function runs in O(N (log N)^2) time on the input size, which
715// would be impossible to do if we were to return all the intersections, which
716// can be quadratic in number.
717std::vector<std::pair<int, int>> FindPartialRectangleIntersections(
718 absl::Span<const Rectangle> rectangles);
719
720// This function is faster that the FindPartialRectangleIntersections() if one
721// only want to know if there is at least one intersection. It is in O(N log N).
722//
723// IMPORTANT: this assumes rectangles are already sorted by their x_min and does
724// not support degenerate rectangles with zero area.
725//
726// If a pair {i, j} is returned, we will have i < j, and no intersection in
727// the subset of rectanges in [0, j).
728std::optional<std::pair<int, int>> FindOneIntersectionIfPresent(
729 absl::Span<const Rectangle> rectangles);
730
731// Same as FindOneIntersectionIfPresent() but supports degenerate rectangles
732// with zero area.
733std::optional<std::pair<int, int>> FindOneIntersectionIfPresentWithZeroArea(
734 absl::Span<const Rectangle> rectangles);
735
736} // namespace sat
737} // namespace operations_research
738
739#endif // OR_TOOLS_SAT_DIFFN_UTIL_H_
void AddMandatoryConsumption(IntegerValue x_min, IntegerValue x_max, IntegerValue y_height)
void AddRectangle(IntegerValue x_min, IntegerValue x_max, IntegerValue y_min, IntegerValue y_max)
Adds a rectangle to the current shape.
void BuildResidualCapacityProfile(std::vector< Rectangle > *result)
IntegerValue GetShrinkDeltaEnergy(Edge edge) const
How much of GetMinimumEnergy() will change if Shrink() is called.
Definition diffn_util.h:592
void Reset()
Reset to the bounding box of the whole set.
IntegerValue GetShrinkDeltaArea(Edge edge) const
How much of GetCurrentRectangleArea() will change if Shrink() is called.
const std::vector< RectangleInRange > & Intervals() const
Definition diffn_util.h:607
ProbingRectangle(const std::vector< RectangleInRange > &intervals)
It will initialize with the bounding box of the whole set.
bool RegionIncludesOther(absl::Span< const Rectangle > region, absl::Span< const Rectangle > other)
The two regions must be defined by non-overlapping rectangles.
Definition diffn_util.h:694
CompactVectorVector< int > GetOverlappingRectangleComponents(absl::Span< const Rectangle > rectangles)
absl::Span< int > FilterBoxesAndRandomize(absl::Span< const Rectangle > cached_rectangles, absl::Span< int > boxes, IntegerValue threshold_x, IntegerValue threshold_y, absl::BitGenRef random)
bool AnalyzeIntervals(bool transpose, absl::Span< const int > local_boxes, absl::Span< const Rectangle > rectangles, absl::Span< const IntegerValue > rectangle_energies, IntegerValue *x_threshold, IntegerValue *y_threshold, Rectangle *conflict)
std::optional< std::pair< int, int > > FindOneIntersectionIfPresent(absl::Span< const Rectangle > rectangles)
double CenterToCenterLInfinityDistance(const Rectangle &a, const Rectangle &b)
Definition diffn_util.h:145
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue.value())
std::vector< Rectangle > FindEmptySpaces(const Rectangle &bounding_box, std::vector< Rectangle > ocupied_rectangles)
absl::Span< int > FilterBoxesThatAreTooLarge(absl::Span< const Rectangle > cached_rectangles, absl::Span< const IntegerValue > energies, absl::Span< int > boxes)
std::vector< int > GetIntervalArticulationPoints(std::vector< IndexedInterval > *intervals)
double CenterToCenterL2Distance(const Rectangle &a, const Rectangle &b)
Returns the L2 distance between the centers of the two rectangles.
Definition diffn_util.h:135
void AppendPairwiseRestrictions(absl::Span< const ItemWithVariableSize > items, std::vector< PairwiseRestriction > *result)
void ConstructOverlappingSets(absl::Span< IndexedInterval > intervals, CompactVectorVector< int > *result, absl::Span< const int > order)
bool ReportEnergyConflict(Rectangle bounding_box, absl::Span< const int > boxes, SchedulingConstraintHelper *x, SchedulingConstraintHelper *y)
FindRectanglesResult FindRectanglesWithEnergyConflictMC(const std::vector< RectangleInRange > &intervals, absl::BitGenRef random, double temperature, double candidate_energy_usage_factor)
std::vector< Rectangle > PavedRegionDifference(std::vector< Rectangle > original_region, absl::Span< const Rectangle > area_to_remove)
bool BoxesAreInEnergyConflict(absl::Span< const Rectangle > rectangles, absl::Span< const IntegerValue > energies, absl::Span< const int > boxes, Rectangle *conflict)
std::optional< std::pair< int, int > > FindOneIntersectionIfPresentWithZeroArea(absl::Span< const Rectangle > rectangles)
std::vector< std::pair< int, int > > FindPartialRectangleIntersections(absl::Span< const Rectangle > rectangles)
IntegerValue Smallest1DIntersection(IntegerValue range_min, IntegerValue range_max, IntegerValue size, IntegerValue interval_min, IntegerValue interval_max)
void GetOverlappingIntervalComponents(std::vector< IndexedInterval > *intervals, std::vector< std::vector< int > > *components)
IntegerValue CapSubI(IntegerValue a, IntegerValue b)
IntegerValue CapProdI(IntegerValue a, IntegerValue b)
Overflows and saturated arithmetic.
std::string RenderDot(std::optional< Rectangle > bb, absl::Span< const Rectangle > solution, std::string_view extra_dot_payload)
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
bool operator==(const Rectangle &other) const
Definition diffn_util.h:335
bool operator<(const Rectangle &other) const
Definition diffn_util.h:334
Rectangle(IntegerValue start, IntegerValue height)
Definition diffn_util.h:331
bool operator()(const IndexedInterval &a, const IndexedInterval &b) const
Definition diffn_util.h:220
bool operator()(const IndexedInterval &a, const IndexedInterval &b) const
Definition diffn_util.h:226
bool operator==(const IndexedInterval &rhs) const
Definition diffn_util.h:212
friend void AbslStringify(Sink &sink, const IndexedInterval &interval)
Definition diffn_util.h:232
friend void AbslStringify(Sink &sink, const ItemWithVariableSize &item)
Definition diffn_util.h:283
bool operator==(const PairwiseRestriction &rhs) const
Definition diffn_util.h:304
Rectangle GetMinimumIntersection(const Rectangle &containing_area) const
Returns an empty rectangle if it is possible for no intersection to happen.
Definition diffn_util.h:472
IntegerValue GetMinimumIntersectionArea(const Rectangle &containing_area) const
Definition diffn_util.h:490
friend void AbslStringify(Sink &sink, const RectangleInRange &r)
Definition diffn_util.h:541
static RectangleInRange BiggestWithMinIntersection(const Rectangle &containing_area, const RectangleInRange &original, const IntegerValue &min_intersect_x, const IntegerValue &min_intersect_y)
Definition diffn_util.h:512
bool operator==(const RectangleInRange &other) const
Definition diffn_util.h:436
Rectangle GetAtCorner(Corner p) const
Definition diffn_util.h:444
bool operator==(const Rectangle &other) const
Definition diffn_util.h:90
void GrowToInclude(const Rectangle &other)
Definition diffn_util.h:50
bool operator!=(const Rectangle &other) const
Definition diffn_util.h:95
absl::InlinedVector< Rectangle, 4 > RegionDifference(const Rectangle &other) const
Definition diffn_util.cc:62
bool IsInsideOf(const Rectangle &other) const
Definition diffn_util.h:74
bool IsDisjoint(const Rectangle &other) const
Definition diffn_util.cc:57
Rectangle Intersect(const Rectangle &other) const
The methods below are not meant to be used with zero-area rectangles.
Definition diffn_util.h:105
IntegerValue IntersectArea(const Rectangle &other) const
Definition diffn_util.h:121
friend void AbslStringify(Sink &sink, const Rectangle &r)
Definition diffn_util.h:85