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