From aeaa20e0ae69157153d1d3f88197f174cc862ba7 Mon Sep 17 00:00:00 2001 From: Florian Fontan Date: Thu, 22 Oct 2026 22:44:54 +0200 Subject: [PATCH] irregular: new linear programming engine for the local search The linear programming engine of the local search is rewritten on top of the population-based iterated local search shared with the direct trigonometry engine. The items may be shrunk instead of overlapping: an item with scale lambda is its shape scaled by lambda around its reference point. For each pair of convex parts close to each other, the edge which separates them the best is selected; the separation constraint is then linear in the positions and the scales. A separation solves linear programs which maximize the separation first, then the weighted sum of the scales, the items staying in a small box around their positions (trust region). The weights of the items which stay shrunk increase, as in guided local search. The perturbation takes the most shrunk item out and inserts it again at a random position, with a random allowed orientation. The previous linear programming engine, with 'linear_programming_minimize_shrinkage' and the parameter 'not_anytime_local_search_maximum_number_of_iterations_without_improvement', is removed. The directories of the engines are renamed 'direct_trigonometry' and 'linear_programming'. 'linear_programming_anchor' moves to 'linear_programming/anchor', and 'find_best_edge_separator' to 'utils.hpp'. --- include/packingsolver/irregular/optimize.hpp | 12 +- python/src/irregular.cpp | 1 - python/tests/test_irregular.py | 3 - src/irregular/CMakeLists.txt | 10 +- .../polygon.cpp | 2 +- .../polygon.hpp | 0 .../separator.cpp | 16 +- .../separator.hpp | 28 +- src/irregular/linear_programming.cpp | 1253 ----------------- src/irregular/linear_programming.hpp | 126 -- src/irregular/linear_programming/anchor.cpp | 481 +++++++ src/irregular/linear_programming/anchor.hpp | 44 + .../linear_programming/separation_model.cpp | 456 ++++++ .../linear_programming/separation_model.hpp | 230 +++ .../linear_programming/separator.cpp | 447 ++++++ .../linear_programming/separator.hpp | 222 +++ src/irregular/local_search.cpp | 423 +----- src/irregular/local_search.hpp | 12 +- src/irregular/main.cpp | 3 - src/irregular/optimize.cpp | 4 - src/irregular/post_process.cpp | 2 +- src/irregular/utils.hpp | 211 ++- test/irregular/linear_programming_test.cpp | 3 +- test/irregular/polygon_test.cpp | 2 +- 24 files changed, 2213 insertions(+), 1778 deletions(-) rename src/irregular/{local_search_direct_trigonometry => direct_trigonometry}/polygon.cpp (99%) rename src/irregular/{local_search_direct_trigonometry => direct_trigonometry}/polygon.hpp (100%) rename src/irregular/{local_search_direct_trigonometry => direct_trigonometry}/separator.cpp (99%) rename src/irregular/{local_search_direct_trigonometry => direct_trigonometry}/separator.hpp (94%) delete mode 100644 src/irregular/linear_programming.cpp delete mode 100644 src/irregular/linear_programming.hpp create mode 100644 src/irregular/linear_programming/anchor.cpp create mode 100644 src/irregular/linear_programming/anchor.hpp create mode 100644 src/irregular/linear_programming/separation_model.cpp create mode 100644 src/irregular/linear_programming/separation_model.hpp create mode 100644 src/irregular/linear_programming/separator.cpp create mode 100644 src/irregular/linear_programming/separator.hpp diff --git a/include/packingsolver/irregular/optimize.hpp b/include/packingsolver/irregular/optimize.hpp index d3897b526..5d5bdc015 100644 --- a/include/packingsolver/irregular/optimize.hpp +++ b/include/packingsolver/irregular/optimize.hpp @@ -265,16 +265,8 @@ struct OptimizeParameters: packingsolver::Parameters Counter not_anytime_sequential_value_correction_number_of_iterations = 32; /** - * Maximum number of iterations without improvement when the local search - * with the linear programming engine packs an item, after which the item - * is considered not to fit. - */ - Counter not_anytime_local_search_maximum_number_of_iterations_without_improvement = 100; - - /** - * Maximum number of failed separations of the local search with the - * direct trigonometry engine, after which a sub-problem is considered - * infeasible. + * Maximum number of failed separations of the local search, after which + * a sub-problem is considered infeasible. * * In 'Anytime' mode, there is no limit: the local search only stops with * the timer. diff --git a/python/src/irregular.cpp b/python/src/irregular.cpp index 9b13f9d5c..c15ea12b3 100644 --- a/python/src/irregular.cpp +++ b/python/src/irregular.cpp @@ -676,7 +676,6 @@ void bind_irregular(nb::module_& m) .def_rw("not_anytime_tree_search_periodic_packing_queue_size", &OptimizeParameters::not_anytime_tree_search_periodic_packing_queue_size) .def_rw("not_anytime_sequential_single_knapsack_subproblem_tree_search_queue_size", &OptimizeParameters::not_anytime_sequential_single_knapsack_subproblem_tree_search_queue_size) .def_rw("not_anytime_sequential_value_correction_number_of_iterations", &OptimizeParameters::not_anytime_sequential_value_correction_number_of_iterations) - .def_rw("not_anytime_local_search_maximum_number_of_iterations_without_improvement", &OptimizeParameters::not_anytime_local_search_maximum_number_of_iterations_without_improvement) .def_rw("not_anytime_local_search_maximum_number_of_failed_separations", &OptimizeParameters::not_anytime_local_search_maximum_number_of_failed_separations) .def_rw("not_anytime_dichotomic_search_subproblem_tree_search_queue_size", &OptimizeParameters::not_anytime_dichotomic_search_subproblem_tree_search_queue_size) .def_rw("reduction_parameters", &OptimizeParameters::reduction_parameters); diff --git a/python/tests/test_irregular.py b/python/tests/test_irregular.py index 2dc686227..a2e08d161 100644 --- a/python/tests/test_irregular.py +++ b/python/tests/test_irregular.py @@ -544,9 +544,6 @@ def test_parameters(): parameters.use_tree_search = True parameters.not_anytime_tree_search_queue_size = 64 assert parameters.not_anytime_tree_search_queue_size == 64 - assert parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement == 100 - parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement = 10 - assert parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement == 10 assert parameters.not_anytime_local_search_maximum_number_of_failed_separations == 10 parameters.not_anytime_local_search_maximum_number_of_failed_separations = 5 assert parameters.not_anytime_local_search_maximum_number_of_failed_separations == 5 diff --git a/src/irregular/CMakeLists.txt b/src/irregular/CMakeLists.txt index 93826bcee..011617a84 100644 --- a/src/irregular/CMakeLists.txt +++ b/src/irregular/CMakeLists.txt @@ -13,17 +13,19 @@ target_sources(PackingSolver_irregular PRIVATE periodic_packing.cpp tree_search.cpp tree_search_periodic_packing.cpp - linear_programming.cpp + linear_programming/anchor.cpp + linear_programming/separation_model.cpp + linear_programming/separator.cpp milp_raster.cpp trivial.cpp - local_search_direct_trigonometry/polygon.cpp - local_search_direct_trigonometry/separator.cpp + direct_trigonometry/polygon.cpp + direct_trigonometry/separator.cpp local_search.cpp sequential_feasibility.cpp reduction.cpp) # Let the compiler vectorize the square roots of the overlap computations. if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - set_source_files_properties(local_search_direct_trigonometry/separator.cpp PROPERTIES COMPILE_OPTIONS "-fno-math-errno") + set_source_files_properties(direct_trigonometry/separator.cpp PROPERTIES COMPILE_OPTIONS "-fno-math-errno") endif() target_include_directories(PackingSolver_irregular PUBLIC ${PROJECT_SOURCE_DIR}/include) diff --git a/src/irregular/local_search_direct_trigonometry/polygon.cpp b/src/irregular/direct_trigonometry/polygon.cpp similarity index 99% rename from src/irregular/local_search_direct_trigonometry/polygon.cpp rename to src/irregular/direct_trigonometry/polygon.cpp index 27994166f..da8649f69 100644 --- a/src/irregular/local_search_direct_trigonometry/polygon.cpp +++ b/src/irregular/direct_trigonometry/polygon.cpp @@ -1,4 +1,4 @@ -#include "irregular/local_search_direct_trigonometry/polygon.hpp" +#include "irregular/direct_trigonometry/polygon.hpp" #include #include diff --git a/src/irregular/local_search_direct_trigonometry/polygon.hpp b/src/irregular/direct_trigonometry/polygon.hpp similarity index 100% rename from src/irregular/local_search_direct_trigonometry/polygon.hpp rename to src/irregular/direct_trigonometry/polygon.hpp diff --git a/src/irregular/local_search_direct_trigonometry/separator.cpp b/src/irregular/direct_trigonometry/separator.cpp similarity index 99% rename from src/irregular/local_search_direct_trigonometry/separator.cpp rename to src/irregular/direct_trigonometry/separator.cpp index 57783fb3f..224cbabb8 100644 --- a/src/irregular/local_search_direct_trigonometry/separator.cpp +++ b/src/irregular/direct_trigonometry/separator.cpp @@ -1,4 +1,4 @@ -#include "irregular/local_search_direct_trigonometry/separator.hpp" +#include "irregular/direct_trigonometry/separator.hpp" #include "irregular/rotations.hpp" #include "irregular/shape_simplification.hpp" @@ -1559,6 +1559,20 @@ void Separator::move_items_workers(const optimizationtools::Timer& timer) copy_state(*workers_[best_worker_pos]); } +bool Separator::separate_initial(const optimizationtools::Timer& timer) +{ + SeparatorParameters parameters = parameters_; + if (initial_maximum_number_of_iterations_without_improvement_ != -1) { + parameters_.maximum_number_of_iterations_without_improvement + = initial_maximum_number_of_iterations_without_improvement_; + } + if (initial_maximum_number_of_strikes_ != -1) + parameters_.maximum_number_of_strikes = initial_maximum_number_of_strikes_; + bool separated = separate(timer); + parameters_ = parameters; + return separated; +} + bool Separator::separate( const optimizationtools::Timer& timer, double reference_loss) diff --git a/src/irregular/local_search_direct_trigonometry/separator.hpp b/src/irregular/direct_trigonometry/separator.hpp similarity index 94% rename from src/irregular/local_search_direct_trigonometry/separator.hpp rename to src/irregular/direct_trigonometry/separator.hpp index c48570fcb..7e389efc8 100644 --- a/src/irregular/local_search_direct_trigonometry/separator.hpp +++ b/src/irregular/direct_trigonometry/separator.hpp @@ -22,7 +22,7 @@ #pragma once -#include "irregular/local_search_direct_trigonometry/polygon.hpp" +#include "irregular/direct_trigonometry/polygon.hpp" #include "packingsolver/irregular/solution.hpp" @@ -203,6 +203,25 @@ class Separator const optimizationtools::Timer& timer, double reference_loss = std::numeric_limits::infinity()); + /** + * Set the stopping criteria of the separation of the initial layout + * ('separate_initial'); -1 means the one of the parameters. + */ + void set_initial_stopping_criteria( + Counter maximum_number_of_iterations_without_improvement, + Counter maximum_number_of_strikes) + { + initial_maximum_number_of_iterations_without_improvement_ + = maximum_number_of_iterations_without_improvement; + initial_maximum_number_of_strikes_ = maximum_number_of_strikes; + } + + /** + * Same as 'separate', with the stopping criteria of the separation of the + * initial layout. + */ + bool separate_initial(const optimizationtools::Timer& timer); + /** * Set the stopping criteria of the next separations * ('SeparatorParameters::maximum_number_of_iterations_without_improvement' @@ -251,6 +270,9 @@ class Separator Point position = {0.0, 0.0}; }; + /** Layout: the states of the items. */ + using Layout = std::vector; + /** Get the layout. */ std::vector layout() const { return items_state_; } @@ -502,6 +524,10 @@ class Separator /** Parameters. */ SeparatorParameters parameters_; + /** Stopping criteria of the separation of the initial layout. */ + Counter initial_maximum_number_of_iterations_without_improvement_ = -1; + Counter initial_maximum_number_of_strikes_ = -1; + /** Random number generator. */ std::mt19937_64 generator_; diff --git a/src/irregular/linear_programming.cpp b/src/irregular/linear_programming.cpp deleted file mode 100644 index 5862e4f24..000000000 --- a/src/irregular/linear_programming.cpp +++ /dev/null @@ -1,1253 +0,0 @@ -#include "irregular/linear_programming.hpp" - -#include "irregular/utils.hpp" -#include "irregular/solution_builder.hpp" - -#ifdef CBC_FOUND -#include "mathoptsolverscmake/mathopt_cbc.hpp" -#endif -#ifdef HIGHS_FOUND -#include "mathoptsolverscmake/mathopt_highs.hpp" -#endif -#ifdef XPRESS_FOUND -#include "mathoptsolverscmake/mathopt_xpress.hpp" -#endif - -using namespace packingsolver; -using namespace packingsolver::irregular; - -namespace -{ - -EdgeSeparationConstraintParameters compute_edge_separation_constraint_parameters( - const Shape& shape_from, - const Point& shift_from, - double scale_from, - ElementPos element_from_pos, - const Shape& shape_to, - const Point& shift_to, - double scale_to) -{ - EdgeSeparationConstraintParameters output; - const ShapeElement& element_from = shape_from.elements[element_from_pos]; - output.distance = std::numeric_limits::infinity(); - for (ElementPos element_to_pos = 0; - element_to_pos < (ElementPos)shape_to.elements.size(); - ++element_to_pos) { - const ShapeElement& element_to = shape_to.elements[element_to_pos]; - const Point& point = element_to.start; - LengthDbl distance = signed_distance_point_to_line( - scale_to * point + shift_to, - scale_from * element_from.start + shift_from, - scale_from * element_from.start + shift_from + (element_from.end - element_from.start)); - LengthDbl distance_unscaled = signed_distance_point_to_line( - point + shift_to, - scale_from * element_from.start + shift_from, - scale_from * element_from.start + shift_from + (element_from.end - element_from.start)); - if (shape::strictly_lesser(distance, output.distance) - || (shape::equal(distance, output.distance) - && shape::strictly_lesser(distance_unscaled, output.distance_unscaled))) { - output.distance = distance; - output.distance_unscaled = distance_unscaled; - output.point_element_pos = element_to_pos; - output.point = point; - } - } - - // Original points: (X11, Y11) (X12, Y12) - // - // Shifted and shrunken points: (x1 + l1 * X11, y1 + l1 * Y11) (x1 + l1 * X12, y1 + l1 * Y12) - // A = l1 * (Y12 - Y11) - // B = l1 * (X11 - X12) - // C = (x1 + l1 * X12) * (y1 + l1 * Y11) - (x1 + l1 * X11) * (y1 + l1 * Y12 - // C = l1 * (x1 * (Y11 - Y12) + y1 * (X12 - X11) + l1 * (X12 Y11 - X11 Y12)) - // - // Simplify by l1: - // A = Y12 - Y11 - // B = X11 - X12 - // C = x1 * (Y11 - Y12) + y1 * (X12 - X11) + l1 * (X12 Y11 - X11 Y12) - // - // Original point: (X2, Y2) - // Shifted and shrunken point: (x2 + l2 * X2, y2 + l2 * Y2) - // Final constraint: - // A * x2 - // + B * y2 - // + (A * X2 + B * Y2) * l2 - // - A * x1 - // - B * y1 - // + (X12 Y11 - X11 Y12) * l1 >= 0 - LengthDbl a = element_from.end.y - element_from.start.y; - LengthDbl b = element_from.start.x - element_from.end.x; - output.coef_x1 = -a; - output.coef_y1 = -b; - output.coef_x2 = a; - output.coef_y2 = b; - output.coef_lambda1 = element_from.end.x * element_from.start.y - - element_from.start.x * element_from.end.y; - output.coef_lambda2 = a * output.point.x + b * output.point.y; - //std::cout << "a " << a << " output.point.x " << output.point.x - // << " prod " << a * output.point.x - // << " b " << b << " output.point.y " << output.point.y - // << " prod " << b * output.point.y << std::endl; - return output; -} - -} - -EdgeSeparationConstraintParameters packingsolver::irregular::find_best_edge_separator( - const Shape& shape_1, - const Point& shift_1, - double scale_1, - const Shape& shape_2, - const Point& shift_2, - double scale_2) -{ - //std::cout << "compute_edge_separation_constraint_parameters" - // << " shape_1 " << shape_1.elements.size() - // << " shift_1 " << shift_1.to_string() - // << " scale_1 " << scale_1 - // << " shape_2 " << shape_2.elements.size() - // << " shift_2 " << shift_2.to_string() - // << " scale_2 " << scale_2 - // << std::endl; - EdgeSeparationConstraintParameters output; - output.distance = -std::numeric_limits::infinity(); - - for (ElementPos element_1_pos = 0; - element_1_pos < (ElementPos)shape_1.elements.size(); - ++element_1_pos) { - const ShapeElement& element = shape_1.elements[element_1_pos]; - EdgeSeparationConstraintParameters p = compute_edge_separation_constraint_parameters( - shape_1, - shift_1, - scale_1, - element_1_pos, - shape_2, - shift_2, - scale_2); - if (output.distance < p.distance) { - output = p; - output.edge_shape_pos = 0; - output.edge_element_pos = element_1_pos; - } - } - - for (ElementPos element_2_pos = 0; - element_2_pos < (ElementPos)shape_2.elements.size(); - ++element_2_pos) { - const ShapeElement& element = shape_2.elements[element_2_pos]; - EdgeSeparationConstraintParameters p = compute_edge_separation_constraint_parameters( - shape_2, - shift_2, - scale_2, - element_2_pos, - shape_1, - shift_1, - scale_1); - if (output.distance < p.distance) { - std::swap(p.coef_x1, p.coef_x2); - std::swap(p.coef_y1, p.coef_y2); - std::swap(p.coef_lambda1, p.coef_lambda2); - output = p; - output.edge_shape_pos = 1; - output.edge_element_pos = element_2_pos; - } - } - - LengthDbl value - = output.coef_x1 * shift_1.x - + output.coef_y1 * shift_1.y - + output.coef_x2 * shift_2.x - + output.coef_y2 * shift_2.y - + output.coef_lambda1 * scale_1 - + output.coef_lambda2 * scale_2; - //if (shape::strictly_lesser(value, 0.0)) { - if (shape::strictly_lesser(value, -1e-6)) { - const ShapeElement& edge_element = ((output.edge_shape_pos == 0)? - shape_1.elements[output.edge_element_pos]: - shape_2.elements[output.edge_element_pos]); - const ShapeElement& point_element = ((output.edge_shape_pos == 0)? - shape_2.elements[output.point_element_pos]: - shape_1.elements[output.point_element_pos]); - throw std::logic_error( - FUNC_SIGNATURE + ": violated separation constraint; " - "edge_element: " + edge_element.to_string() + "; " - "point_element: " + point_element.to_string() + "; " - "point: " + output.point.to_string() + "; " - "distance: " + std::to_string(output.distance) + "; " - "coef_x1: " + std::to_string(output.coef_x1) + "; " - "coef_y1: " + std::to_string(output.coef_y1) + "; " - "coef_lambda1: " + std::to_string(output.coef_lambda1) + "; " - "coef_x2: " + std::to_string(output.coef_x2) + "; " - "coef_y2: " + std::to_string(output.coef_y2) + "; " - "coef_lambda2: " + std::to_string(output.coef_lambda2) + "; " - "value: " + std::to_string(value) + "."); - } - - return output; -} - -namespace -{ - -Solution linear_programming_anchor( - const Instance& instance, - const Solution& initial_solution, - double x_weight, - double y_weight, - const LinearProgrammingAnchorParameters& parameters, - const InstanceBasicShapeDecomposition& icd) -{ - // Check that the solution has a single bin. - if (initial_solution.number_of_bins() != 1) { - throw std::invalid_argument( - FUNC_SIGNATURE); - } - - // Get bin type. - const BinPos bin_pos = 0; - const BinTypeId bin_type_id = initial_solution.bin(bin_pos).bin_type_id; - const BinType& bin_type = instance.bin_type(bin_type_id); - - // Compute fixed and unfixed items. - std::vector fixed_items; - std::vector unfixed_items; - for (ItemPos item_pos = 0; - item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); - ++item_pos) { - const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; - if (solution_item.is_fixed) { - fixed_items.push_back(item_pos); - } else { - unfixed_items.push_back(item_pos); - } - } - - // Precompute rotated convex decompositions for each solution item. - // item_rotated_decompositions[item_pos][item_shape_pos] = list of convex parts - // with the item's angle and mirror already applied. - std::vector>> item_rotated_decompositions(initial_solution.bin(bin_pos).items.size()); - for (ItemPos item_pos = 0; - item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); - ++item_pos) { - const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; - const ItemType& item_type = instance.item_type(solution_item.item_type_id); - item_rotated_decompositions[item_pos].resize(item_type.shapes.size()); - for (ItemShapePos item_shape_pos = 0; - item_shape_pos < (ItemShapePos)item_type.shapes.size(); - ++item_shape_pos) { - for (const BasicShape& basic_shape: icd.item_types[solution_item.item_type_id][item_shape_pos]) { - item_rotated_decompositions[item_pos][item_shape_pos].push_back( - apply_placement(basic_shape, solution_item.mirror, solution_item.angle)); - } - } - } - - // Precompute AABBs for fixed items, border and defect convex parts (fixed world coordinates). - std::vector fixed_item_part_aabbs; - for (ItemPos item_pos = 0; - item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); - ++item_pos) { - const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; - if (!solution_item.is_fixed) - continue; - const LengthDbl cx = solution_item.bl_corner.x * instance.parameters().scale_value; - const LengthDbl cy = solution_item.bl_corner.y * instance.parameters().scale_value; - for (ItemShapePos item_shape_pos = 0; - item_shape_pos < (ItemShapePos)item_rotated_decompositions[item_pos].size(); - ++item_shape_pos) { - const auto& parts = item_rotated_decompositions[item_pos][item_shape_pos]; - for (Counter part_pos = 0; part_pos < (Counter)parts.size(); ++part_pos) { - const AxisAlignedBoundingBox p = parts[part_pos].shape.compute_min_max(); - AxisAlignedBoundingBox ps; - ps.x_min = cx + p.x_min; - ps.x_max = cx + p.x_max; - ps.y_min = cy + p.y_min; - ps.y_max = cy + p.y_max; - fixed_item_part_aabbs.push_back(ps); - } - } - } - std::vector border_part_aabbs; - for (const BasicShape& part: icd.bin_types_borders[bin_type_id]) - border_part_aabbs.push_back(part.shape.compute_min_max()); - std::vector defect_part_aabbs; - for (const BasicShape& part: icd.bin_types_defects[bin_type_id]) - defect_part_aabbs.push_back(part.shape.compute_min_max()); - - LengthDbl movement_box_half_size = 10; - - Solution solution = initial_solution; - double current_value = 0; - for (const SolutionItem& solution_item: initial_solution.bin(bin_pos).items) { - current_value += x_weight * solution_item.bl_corner.x * instance.parameters().scale_value; - current_value += y_weight * solution_item.bl_corner.y * instance.parameters().scale_value; - } - // Lambda is fixed at 1 for anchor_to_corner (no shrinkage variables). - const std::vector anchor_lambda(initial_solution.bin(bin_pos).items.size(), 1.0); - - for (Counter number_of_iterations = 0;; ++number_of_iterations) { - const SolutionBin& solution_bin = solution.bin(bin_pos); - - const std::vector unfixed_item_aabbs = compute_unfixed_item_aabbs( - instance, - solution_bin, - movement_box_half_size, - item_rotated_decompositions, - anchor_lambda); - - // Precompute per-item bin bounds (without movement restriction). - // The local bounding box of each item is read from item_aabbs. - std::vector item_bin_bounds(unfixed_items.size()); - for (ItemPos item_var_pos = 0; - item_var_pos < (ItemPos)unfixed_items.size(); - ++item_var_pos) { - const AxisAlignedBoundingBox& ia = unfixed_item_aabbs[item_var_pos].item_aabb; - LengthDbl x_min = (x_weight < 0)? solution.x_min(): bin_type.aabb_orig.x_min; - LengthDbl x_max = (x_weight > 0)? solution.x_max(): bin_type.aabb_orig.x_max; - LengthDbl y_min = (y_weight < 0)? solution.y_min(): bin_type.aabb_orig.y_min; - LengthDbl y_max = (y_weight > 0)? solution.y_max(): bin_type.aabb_orig.y_max; - item_bin_bounds[item_var_pos].x_min = x_min * instance.parameters().scale_value - ia.x_min; - item_bin_bounds[item_var_pos].x_max = x_max * instance.parameters().scale_value - ia.x_max; - item_bin_bounds[item_var_pos].y_min = y_min * instance.parameters().scale_value - ia.y_min; - item_bin_bounds[item_var_pos].y_max = y_max * instance.parameters().scale_value - ia.y_max; - } - - IntersectingParts intersecting_parts = compute_potentially_intersecting_parts( - unfixed_item_aabbs, - fixed_item_part_aabbs, - border_part_aabbs, - defect_part_aabbs); - - //////////////////// - // Setup LP model // - //////////////////// - - // Build LP model. - mathoptsolverscmake::MathOptModel lp_model; - - ///////////////////////////// - // Objective and variables // - ///////////////////////////// - - // Set objective sense. - lp_model.objective_direction = mathoptsolverscmake::ObjectiveDirection::Minimize; - - std::vector x(solution_bin.items.size(), -1); - std::vector y(solution_bin.items.size(), -1); - for (ItemPos item_var_pos = 0; - item_var_pos < (ItemPos)unfixed_items.size(); - ++item_var_pos) { - ItemPos item_pos = unfixed_items[item_var_pos]; - const SolutionItem& solution_item = solution_bin.items[item_pos]; - - x[item_pos] = lp_model.variables_lower_bounds.size(); - lp_model.variables_lower_bounds.push_back(std::max( - item_bin_bounds[item_var_pos].x_min, - solution_item.bl_corner.x * instance.parameters().scale_value - movement_box_half_size)); - lp_model.variables_upper_bounds.push_back(std::min( - item_bin_bounds[item_var_pos].x_max, - solution_item.bl_corner.x * instance.parameters().scale_value +movement_box_half_size)); - lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); - lp_model.objective_coefficients.push_back(x_weight); - lp_model.variables_names.push_back("x_" + std::to_string(item_pos)); - - y[item_pos] = lp_model.variables_lower_bounds.size(); - lp_model.variables_lower_bounds.push_back(std::max( - item_bin_bounds[item_var_pos].y_min, - solution_item.bl_corner.y * instance.parameters().scale_value - movement_box_half_size)); - lp_model.variables_upper_bounds.push_back(std::min( - item_bin_bounds[item_var_pos].y_max, - solution_item.bl_corner.y * instance.parameters().scale_value + movement_box_half_size)); - lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); - lp_model.objective_coefficients.push_back(y_weight); - lp_model.variables_names.push_back("y_" + std::to_string(item_pos)); - } - - ///////////////// - // Constraints // - ///////////////// - - // Obstacle (shape_1) is at world origin with scale=1 (fixed). - // Item (shape_2) has LP variables x, y at scale=1 (no lambda in atc). - // Full constraint: coef_x1*0 + coef_y1*0 + coef_lambda1 + coef_x2*x + coef_y2*y + coef_lambda2 >= 0 - // => coef_x2*x + coef_y2*y >= -(coef_lambda1 + coef_lambda2) - - const LengthDbl sv = instance.parameters().scale_value; - - // Intersections between an unifxed item and a fixed item. - for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_part_fixed_item_part) { - ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; - ItemPos item_2_pos = fixed_items[e.item_2_var_pos]; - const SolutionItem& item_1 = solution_bin.items[item_1_pos]; - const SolutionItem& item_2 = solution_bin.items[item_2_pos]; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape, - sv * item_1.bl_corner, - 1.0, - item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape, - sv * item_2.bl_corner, - 1.0); - if (shape::equal(p.coef_x1, 0.0) && shape::equal(p.coef_y1, 0.0)) - continue; - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "sep_fixed_i_" + std::to_string(item_1_pos) - + "_s" + std::to_string(e.item_shape_1_pos) - + "_p" + std::to_string(e.item_part_1_pos) - + "_i" + std::to_string(item_2_pos) - + "_s" + std::to_string(e.item_shape_2_pos) - + "_p" + std::to_string(e.item_part_2_pos)); - lp_model.constraints_lower_bounds.push_back( - -p.coef_x2 * item_2.bl_corner.x * sv - -p.coef_y2 * item_2.bl_corner.y * sv - -p.coef_lambda2 - -p.coef_lambda1); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - } - - // Intersections between items and bin borders. - for (const IntersectingItemPartDefectPart& e: intersecting_parts.intersecting_item_part_border_part) { - ItemPos item_pos = unfixed_items[e.item_var_pos]; - const SolutionItem& item = solution_bin.items[item_pos]; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - item_rotated_decompositions[item_pos][e.item_shape_pos][e.item_part_pos].shape, - sv * item.bl_corner, - 1.0, - icd.bin_types_borders[bin_type_id][e.defect_pos].shape, - Point{0, 0}, - 1.0); - if (shape::equal(p.coef_x1, 0.0) && shape::equal(p.coef_y1, 0.0)) - continue; - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "border_i" + std::to_string(item_pos) - + "_s" + std::to_string(e.item_shape_pos) - + "_p" + std::to_string(e.item_part_pos) - + "_bp" + std::to_string(e.defect_pos)); - lp_model.constraints_lower_bounds.push_back(-p.coef_lambda2 - p.coef_lambda1); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - } - - // Intersections between items and bin defects. - for (const IntersectingItemPartDefectPart& e: intersecting_parts.intersecting_item_part_defect_part) { - ItemPos item_pos = unfixed_items[e.item_var_pos]; - const SolutionItem& item = solution_bin.items[item_pos]; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - item_rotated_decompositions[item_pos][e.item_shape_pos][e.item_part_pos].shape, - sv * item.bl_corner, - 1.0, - icd.bin_types_defects[bin_type_id][e.defect_pos].shape, - Point{0, 0}, - 1.0); - if (shape::equal(p.coef_x1, 0.0) && shape::equal(p.coef_y1, 0.0)) - continue; - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "defect_i" + std::to_string(e.item_var_pos) - + "_s" + std::to_string(e.item_shape_pos) - + "_p" + std::to_string(e.item_part_pos) - + "_dp" + std::to_string(e.defect_pos)); - lp_model.constraints_lower_bounds.push_back(-p.coef_lambda2 - p.coef_lambda1); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - } - - // Intersections between pairs of items. - // Full constraint: coef_x1*x1 + coef_y1*y1 + coef_lambda1 + coef_x2*x2 + coef_y2*y2 + coef_lambda2 >= 0 - // => coef_x1*x1 + coef_y1*y1 + coef_x2*x2 + coef_y2*y2 >= -(coef_lambda1 + coef_lambda2) - for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_parts) { - ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; - ItemPos item_2_pos = unfixed_items[e.item_2_var_pos]; - const SolutionItem& item_1 = solution_bin.items[item_1_pos]; - const SolutionItem& item_2 = solution_bin.items[item_2_pos]; - const Shape& convex_part_1 = item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape; - const Shape& convex_part_2 = item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - convex_part_1, - sv * item_1.bl_corner, - 1.0, // scale - convex_part_2, - sv * item_2.bl_corner, - 1.0); // scale - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "sep_i" + std::to_string(e.item_1_var_pos) - + "_s" + std::to_string(e.item_shape_1_pos) - + "_p" + std::to_string(e.item_part_1_pos) - + "_i" + std::to_string(e.item_2_var_pos) - + "_s" + std::to_string(e.item_shape_2_pos) - + "_p" + std::to_string(e.item_part_2_pos)); - lp_model.constraints_lower_bounds.push_back(-(p.coef_lambda1 + p.coef_lambda2)); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - if (!shape::equal(p.coef_x2, 0.0)) { - lp_model.elements_variables.push_back(x[item_2_pos]); - lp_model.elements_coefficients.push_back(p.coef_x2); - } - if (!shape::equal(p.coef_y2, 0.0)) { - lp_model.elements_variables.push_back(y[item_2_pos]); - lp_model.elements_coefficients.push_back(p.coef_y2); - } - } - - //lp_model.feasiblity_tolerance = 1e-3; - //lp_model.check(1); - //lp_model.format(std::cout, 4); - - std::vector lp_initial_solution(lp_model.variables_lower_bounds.size()); - for (ItemPos item_var_pos = 0; - item_var_pos < (ItemPos)unfixed_items.size(); - ++item_var_pos) { - ItemPos item_pos = unfixed_items[item_var_pos]; - const SolutionItem& solution_item = solution_bin.items[item_pos]; - lp_initial_solution[x[item_pos]] = solution_item.bl_corner.x * sv; - lp_initial_solution[y[item_pos]] = solution_item.bl_corner.y * sv; - } - lp_model.variables_initial_values = lp_initial_solution; - //lp_model.format_solution(std::cout, lp_initial_solution, 4); - //lp_model.check_solution(lp_initial_solution, 1); - - /////////// - // Solve // - /////////// - - std::vector lp_solution; - if (parameters.solver == mathoptsolverscmake::SolverName::Highs) { -#ifdef HIGHS_FOUND - Highs highs; - mathoptsolverscmake::reduce_printout(highs); - mathoptsolverscmake::set_time_limit(highs, parameters.timer.remaining_time()); - highs.setOptionValue("parallel", "off"); - //mathoptsolverscmake::set_log_file(highs, "highs.log"); - mathoptsolverscmake::load(highs, lp_model); - //std::cout << "LP solve start" << std::endl; - mathoptsolverscmake::solve(highs); - //std::cout << "LP solve end" << std::endl; - if (highs.getModelStatus() != HighsModelStatus::kOptimal) { - // If the time limit is reached, keep the current solution. - if (parameters.timer.needs_to_end()) - break; - throw std::runtime_error( - FUNC_SIGNATURE + ": LP not solved to optimality; " - "model status: " + highs.modelStatusToString(highs.getModelStatus()) + "."); - } - lp_solution = mathoptsolverscmake::get_solution(highs); -#else - throw std::invalid_argument(FUNC_SIGNATURE); -#endif - - } else { - throw std::invalid_argument(FUNC_SIGNATURE); - } - - double new_value = lp_model.evaluate_objective(lp_solution); - - // If the solution of the MILP model is not better, stop. - if (!shape::strictly_greater(current_value, new_value)) - break; - current_value = new_value; - - // Retrieve solution. - SolutionBuilder new_solution_builder(instance); - new_solution_builder.add_bin(solution_bin.bin_type_id, 1); - for (ItemPos pos = 0; pos < (ItemPos)solution_bin.items.size(); ++pos) { - const SolutionItem& solution_item = solution_bin.items[pos]; - if (solution_item.is_fixed) { - new_solution_builder.add_item( - 0, - solution_item.item_type_id, - solution_item.bl_corner, - solution_item.angle, - solution_item.mirror, - true); - } else { - new_solution_builder.add_item( - 0, - solution_item.item_type_id, - {lp_solution[x[pos]] / instance.parameters().scale_value, lp_solution[y[pos]] / instance.parameters().scale_value}, - solution_item.angle, - solution_item.mirror); - } - } - solution = new_solution_builder.build(); - } - - return solution; -} - -} - -LinearProgrammingAnchorOutput packingsolver::irregular::linear_programming_anchor( - const Solution& initial_solution, - double x_weight, - double y_weight, - const LinearProgrammingAnchorParameters& parameters) -{ - //std::cout << "linear_programming" << std::endl; - const Instance& instance = initial_solution.instance(); - LinearProgrammingAnchorOutput output(instance); - - const InstanceBasicShapeDecomposition icd = compute_instance_basic_shape_decomposition(instance); - - Solution solution(instance); - for (BinPos bin_pos = 0; - bin_pos < initial_solution.number_of_different_bins(); - ++bin_pos) { - const SolutionBin& solution_bin = initial_solution.bin(bin_pos); - Solution initial_solution_cur(instance); - initial_solution_cur.append_bin(initial_solution, bin_pos, 1); - Solution new_solution_cur = ::linear_programming_anchor( - instance, - initial_solution_cur, - x_weight, - y_weight, - parameters, - icd); - solution.append_bin( - new_solution_cur, - 0, - solution_bin.copies); - } - //initial_solution.format(std::cout, 1); - //solution.format(std::cout, 1); - output.solution = solution; - - //instance.write("lp_test.json"); - //initial_solution.write("lp_test_initial.json"); - //solution.write("lp_test_expected.json"); - //exit(1); - //std::cout << "linear_programming end" << std::endl; - return output; -} - -LinearProgrammingMinimizeShrinkageOutput packingsolver::irregular::linear_programming_minimize_shrinkage( - const Solution& initial_solution, - const std::vector& initial_lambda, - const std::vector& item_penalties, - const LinearProgrammingMinimizeShrinkageParameters& parameters) -{ - const Instance& instance = initial_solution.instance(); - LinearProgrammingMinimizeShrinkageOutput output(instance); - - // Check that the solution has a single bin. - if (initial_solution.number_of_bins() != 1) { - throw std::invalid_argument( - FUNC_SIGNATURE); - } - - const BinPos bin_pos = 0; - const BinTypeId bin_type_id = initial_solution.bin(bin_pos).bin_type_id; - const BinType& bin_type = instance.bin_type(bin_type_id); - - const InstanceBasicShapeDecomposition icd = compute_instance_basic_shape_decomposition(instance); - - // Compute fixed and unfixed items. - std::vector fixed_items; - std::vector unfixed_items; - for (ItemPos item_pos = 0; - item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); - ++item_pos) { - const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; - if (solution_item.is_fixed) { - fixed_items.push_back(item_pos); - } else { - unfixed_items.push_back(item_pos); - } - } - - // Precompute rotated convex decompositions. - std::vector>> item_rotated_decompositions( - initial_solution.bin(bin_pos).items.size()); - for (ItemPos item_pos = 0; - item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); - ++item_pos) { - const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; - const ItemType& item_type = instance.item_type(solution_item.item_type_id); - item_rotated_decompositions[item_pos].resize(item_type.shapes.size()); - for (ItemShapePos item_shape_pos = 0; - item_shape_pos < (ItemShapePos)item_type.shapes.size(); - ++item_shape_pos) { - for (const BasicShape& basic_shape: icd.item_types[solution_item.item_type_id][item_shape_pos]) { - item_rotated_decompositions[item_pos][item_shape_pos].push_back( - apply_placement(basic_shape, solution_item.mirror, solution_item.angle)); - } - } - } - - // Precompute AABBs for fixed items, border and defect convex parts (fixed world coordinates). - std::vector fixed_item_part_aabbs; - for (ItemPos item_pos = 0; - item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); - ++item_pos) { - const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; - if (!solution_item.is_fixed) - continue; - const LengthDbl cx = solution_item.bl_corner.x * instance.parameters().scale_value; - const LengthDbl cy = solution_item.bl_corner.y * instance.parameters().scale_value; - for (ItemShapePos item_shape_pos = 0; - item_shape_pos < (ItemShapePos)item_rotated_decompositions[item_pos].size(); - ++item_shape_pos) { - const auto& parts = item_rotated_decompositions[item_pos][item_shape_pos]; - for (Counter part_pos = 0; part_pos < (Counter)parts.size(); ++part_pos) { - const AxisAlignedBoundingBox p = parts[part_pos].shape.compute_min_max(); - AxisAlignedBoundingBox ps; - ps.x_min = cx + p.x_min; - ps.x_max = cx + p.x_max; - ps.y_min = cy + p.y_min; - ps.y_max = cy + p.y_max; - fixed_item_part_aabbs.push_back(ps); - } - } - } - std::vector border_part_aabbs; - for (const BasicShape& part: icd.bin_types_borders[bin_type_id]) - border_part_aabbs.push_back(part.shape.compute_min_max()); - std::vector defect_part_aabbs; - for (const BasicShape& part: icd.bin_types_defects[bin_type_id]) - defect_part_aabbs.push_back(part.shape.compute_min_max()); - - const LengthDbl sv = instance.parameters().scale_value; - const LengthDbl movement_box_half_size = 10; - const double lambda_delta = 0.2; - - Solution solution = initial_solution; - double current_value = 0; - std::vector current_items_shrunken(solution.bin(bin_pos).items.size(), true); - std::vector current_lambda = initial_lambda; - - for (Counter number_of_iterations = 0;; ++number_of_iterations) { - //std::cout << "number_of_iterations " << number_of_iterations << std::endl; - const SolutionBin& solution_bin = solution.bin(bin_pos); - - std::vector unfixed_item_aabbs = compute_unfixed_item_aabbs( - instance, - solution_bin, - movement_box_half_size, - item_rotated_decompositions, - current_lambda); - - IntersectingParts intersecting_parts = compute_potentially_intersecting_parts( - unfixed_item_aabbs, - fixed_item_part_aabbs, - border_part_aabbs, - defect_part_aabbs); - - //////////////////// - // Setup LP model // - //////////////////// - - mathoptsolverscmake::MathOptModel lp_model; - - ///////////////////////////// - // Objective and variables // - ///////////////////////////// - - // Position variables (objective coefficient 0) and lambda variables - // (objective coefficient -penalty; minimizing -sum(lambda*penalty) maximizes lambda). - lp_model.objective_direction = mathoptsolverscmake::ObjectiveDirection::Maximize; - std::vector x(solution_bin.items.size(), -1); - std::vector y(solution_bin.items.size(), -1); - std::vector lambda_var(solution_bin.items.size(), -1); - for (ItemPos item_var_pos = 0; - item_var_pos < (ItemPos)unfixed_items.size(); - ++item_var_pos) { - ItemPos item_pos = unfixed_items[item_var_pos]; - const SolutionItem& solution_item = solution_bin.items[item_pos]; - - x[item_pos] = lp_model.variables_lower_bounds.size(); - lp_model.variables_lower_bounds.push_back(-std::numeric_limits::infinity()); - lp_model.variables_upper_bounds.push_back(+std::numeric_limits::infinity()); - lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); - lp_model.objective_coefficients.push_back(0.0); - lp_model.variables_names.push_back("x_" + std::to_string(item_pos)); - - y[item_pos] = lp_model.variables_lower_bounds.size(); - lp_model.variables_lower_bounds.push_back(-std::numeric_limits::infinity()); - lp_model.variables_upper_bounds.push_back(+std::numeric_limits::infinity()); - lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); - lp_model.objective_coefficients.push_back(0.0); - lp_model.variables_names.push_back("y_" + std::to_string(item_pos)); - - lambda_var[item_pos] = lp_model.variables_lower_bounds.size(); - lp_model.variables_lower_bounds.push_back(0.0); - lp_model.variables_upper_bounds.push_back(1.0); - lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); - lp_model.objective_coefficients.push_back(item_penalties[item_pos]); - lp_model.variables_names.push_back("lambda_" + std::to_string(item_pos)); - } - - ///////////////// - // Constraints // - ///////////////// - - // Bin containment per convex part: x_j + x_max_l_p * lambda_j <= x_max_p, etc. - // Coefficients come from part_aabbs; RHS from part_movement_aabbs clamped to bin. - for (ItemPos item_var_pos = 0; - item_var_pos < (ItemPos)unfixed_items.size(); - ++item_var_pos) { - ItemPos item_pos = unfixed_items[item_var_pos]; - for (ItemShapePos shape_pos = 0; - shape_pos < (ItemShapePos)unfixed_item_aabbs[item_var_pos].part_aabbs.size(); - ++shape_pos) { - for (Counter part_pos = 0; - part_pos < (Counter)unfixed_item_aabbs[item_var_pos].part_aabbs[shape_pos].size(); - ++part_pos) { - const AxisAlignedBoundingBox& pa = - unfixed_item_aabbs[item_var_pos].part_aabbs[shape_pos][part_pos]; - const AxisAlignedBoundingBox& pm = - unfixed_item_aabbs[item_var_pos].part_movement_aabbs[shape_pos][part_pos]; - - // RHS: part movement AABB clamped to bin bounds. - const LengthDbl x_min = (std::max)(pm.x_min, bin_type.aabb_scaled.x_min); - const LengthDbl x_max = (std::min)(pm.x_max, bin_type.aabb_scaled.x_max); - const LengthDbl y_min = (std::max)(pm.y_min, bin_type.aabb_scaled.y_min); - const LengthDbl y_max = (std::min)(pm.y_max, bin_type.aabb_scaled.y_max); - - const std::string sid = std::to_string(item_pos) - + "_s" + std::to_string(shape_pos) - + "_p" + std::to_string(part_pos); - - // x_j + x_max_l_p * lambda_j <= x_max_p - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back("bin_x_max_i" + sid); - lp_model.constraints_lower_bounds.push_back(-std::numeric_limits::infinity()); - lp_model.constraints_upper_bounds.push_back(x_max); - lp_model.elements_variables.push_back(x[item_pos]); - lp_model.elements_coefficients.push_back(1.0); - lp_model.elements_variables.push_back(lambda_var[item_pos]); - lp_model.elements_coefficients.push_back(pa.x_max); - - // x_j + x_min_l_p * lambda_j >= x_min_p - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back("bin_x_min_i" + sid); - lp_model.constraints_lower_bounds.push_back(x_min); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - lp_model.elements_variables.push_back(x[item_pos]); - lp_model.elements_coefficients.push_back(1.0); - lp_model.elements_variables.push_back(lambda_var[item_pos]); - lp_model.elements_coefficients.push_back(pa.x_min); - - // y_j + y_max_l_p * lambda_j <= y_max_p - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back("bin_y_max_i" + sid); - lp_model.constraints_lower_bounds.push_back(-std::numeric_limits::infinity()); - lp_model.constraints_upper_bounds.push_back(y_max); - lp_model.elements_variables.push_back(y[item_pos]); - lp_model.elements_coefficients.push_back(1.0); - lp_model.elements_variables.push_back(lambda_var[item_pos]); - lp_model.elements_coefficients.push_back(pa.y_max); - - // y_j + y_min_l_p * lambda_j >= y_min_p - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back("bin_y_min_i" + sid); - lp_model.constraints_lower_bounds.push_back(y_min); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - lp_model.elements_variables.push_back(y[item_pos]); - lp_model.elements_coefficients.push_back(1.0); - lp_model.elements_variables.push_back(lambda_var[item_pos]); - lp_model.elements_coefficients.push_back(pa.y_min); - } - } - } - - // Obstacle (shape_1) is at world origin with lambda=1 (fixed). - // Item (shape_2) has LP variables x, y, lambda. - // Full constraint: coef_x1*0 + coef_y1*0 + coef_lambda1*1 - // + coef_x2*x + coef_y2*y + coef_lambda2*lambda >= 0 - // => coef_x2*x + coef_y2*y + coef_lambda2*lambda >= -coef_lambda1 - - // Intersections between an unifxed item and a fixed item. - for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_part_fixed_item_part) { - ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; - ItemPos item_2_pos = fixed_items[e.item_2_var_pos]; - const SolutionItem& item_1 = solution_bin.items[item_1_pos]; - const SolutionItem& item_2 = solution_bin.items[item_2_pos]; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape, - sv * item_1.bl_corner, - current_lambda[item_1_pos], - item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape, - sv * item_2.bl_corner, - current_lambda[item_2_pos]); - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "sep_fixed_i_" + std::to_string(item_1_pos) - + "_s" + std::to_string(e.item_shape_1_pos) - + "_p" + std::to_string(e.item_part_1_pos) - + "_i" + std::to_string(item_2_pos) - + "_s" + std::to_string(e.item_shape_2_pos) - + "_p" + std::to_string(e.item_part_2_pos)); - lp_model.constraints_lower_bounds.push_back( - -p.coef_x2 * item_2.bl_corner.x * sv - -p.coef_y2 * item_2.bl_corner.y * sv - -p.coef_lambda2); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - if (!shape::equal(p.coef_lambda1, 0.0)) { - lp_model.elements_variables.push_back(lambda_var[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_lambda1); - } - } - - // Intersections between items and bin borders. - for (const IntersectingItemPartDefectPart& e: intersecting_parts.intersecting_item_part_border_part) { - ItemPos item_pos = unfixed_items[e.item_var_pos]; - const SolutionItem& item = solution_bin.items[item_pos]; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - item_rotated_decompositions[item_pos][e.item_shape_pos][e.item_part_pos].shape, - sv * item.bl_corner, - current_lambda[item_pos], - icd.bin_types_borders[bin_type_id][e.defect_pos].shape, - {0, 0}, - 1.0); - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "border_i" + std::to_string(item_pos) - + "_s" + std::to_string(e.item_shape_pos) - + "_p" + std::to_string(e.item_part_pos) - + "_bp" + std::to_string(e.defect_pos)); - lp_model.constraints_lower_bounds.push_back(-p.coef_lambda2); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - if (!shape::equal(p.coef_lambda1, 0.0)) { - lp_model.elements_variables.push_back(lambda_var[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_lambda1); - } - } - - // Intersections between items and bin defects. - for (const IntersectingItemPartDefectPart& e: intersecting_parts.intersecting_item_part_defect_part) { - ItemPos item_pos = unfixed_items[e.item_var_pos]; - const SolutionItem& item = solution_bin.items[item_pos]; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - item_rotated_decompositions[item_pos][e.item_shape_pos][e.item_part_pos].shape, - sv * item.bl_corner, - current_lambda[item_pos], - icd.bin_types_defects[bin_type_id][e.defect_pos].shape, - {0, 0}, - 1.0); - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back( - "defect_i" + std::to_string(item_pos) - + "_s" + std::to_string(e.item_shape_pos) - + "_p" + std::to_string(e.item_part_pos) - + "_dp" + std::to_string(e.defect_pos)); - lp_model.constraints_lower_bounds.push_back(-p.coef_lambda2); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - if (!shape::equal(p.coef_lambda1, 0.0)) { - lp_model.elements_variables.push_back(lambda_var[item_pos]); - lp_model.elements_coefficients.push_back(p.coef_lambda1); - } - } - - for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_parts) { - ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; - ItemPos item_2_pos = unfixed_items[e.item_2_var_pos]; - const SolutionItem& item_1 = solution_bin.items[item_1_pos]; - const SolutionItem& item_2 = solution_bin.items[item_2_pos]; - const Shape& convex_part_1 = item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape; - const Shape& convex_part_2 = item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape; - std::string constraint_name - = "sep_i" + std::to_string(e.item_1_var_pos) - + "_s" + std::to_string(e.item_shape_1_pos) - + "_p" + std::to_string(e.item_part_1_pos) - + "_i" + std::to_string(e.item_2_var_pos) - + "_s" + std::to_string(e.item_shape_2_pos) - + "_p" + std::to_string(e.item_part_2_pos); - //std::cout << "item_1_pos " << e.item_1_var_pos - // << " item_type_1 " << item_1.item_type_id - // << " item_1_shape_pos " << e.item_shape_1_pos - // << " item_1_part_pos " << e.item_part_1_pos - // << " bl_corner " << (sv * item_1.bl_corner).to_string() - // << " angle " << item_1.angle - // << " mirror " << item_1.mirror - // << std::endl; - //std::cout << "item_2_pos " << e.item_2_var_pos - // << " item_type_2 " << item_2.item_type_id - // << " item_2_shape_pos " << e.item_shape_2_pos - // << " item_2_part_pos " << e.item_part_2_pos - // << " bl_corner " << (sv * item_2.bl_corner).to_string() - // << " angle " << item_2.angle - // << " mirror " << item_2.mirror - // << std::endl; - //std::cout << "constraint " << constraint_name << std::endl; - const EdgeSeparationConstraintParameters p = find_best_edge_separator( - convex_part_1, - sv * item_1.bl_corner, - current_lambda[item_1_pos], - convex_part_2, - sv * item_2.bl_corner, - current_lambda[item_2_pos]); - //std::cout << "shape_pos " << p.edge_shape_pos - // << " edge_element_pos " << p.edge_element_pos - // << " point_element_pos " << p.point_element_pos - // << " distance " << p.distance - // << std::endl; - //std::cout << "edge_element " << ((p.edge_shape_pos == 0)? - // convex_part_1.elements[p.edge_element_pos].to_string(): - // convex_part_2.elements[p.edge_element_pos].to_string()) << std::endl; - //std::cout << "point_element " << ((p.edge_shape_pos == 0)? - // convex_part_2.elements[p.point_element_pos].to_string(): - // convex_part_1.elements[p.point_element_pos].to_string()) << std::endl; - //std::cout << "point " << p.point.to_string() << std::endl; - //std::cout << "coef_x1 " << p.coef_x1 << " coef_y1 " << p.coef_y1 << " coef_lambda1 " << p.coef_lambda1 << std::endl; - //std::cout << "coef_x2 " << p.coef_x2 << " coef_y2 " << p.coef_y2 << " coef_lambda2 " << p.coef_lambda2 << std::endl; - lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); - lp_model.constraints_names.push_back(constraint_name); - lp_model.constraints_lower_bounds.push_back(0.0); - lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); - if (!shape::equal(p.coef_x1, 0.0)) { - lp_model.elements_variables.push_back(x[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_x1); - } - if (!shape::equal(p.coef_y1, 0.0)) { - lp_model.elements_variables.push_back(y[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_y1); - } - if (!shape::equal(p.coef_lambda1, 0.0)) { - lp_model.elements_variables.push_back(lambda_var[item_1_pos]); - lp_model.elements_coefficients.push_back(p.coef_lambda1); - } - if (!shape::equal(p.coef_x2, 0.0)) { - lp_model.elements_variables.push_back(x[item_2_pos]); - lp_model.elements_coefficients.push_back(p.coef_x2); - } - if (!shape::equal(p.coef_y2, 0.0)) { - lp_model.elements_variables.push_back(y[item_2_pos]); - lp_model.elements_coefficients.push_back(p.coef_y2); - } - if (!shape::equal(p.coef_lambda2, 0.0)) { - lp_model.elements_variables.push_back(lambda_var[item_2_pos]); - lp_model.elements_coefficients.push_back(p.coef_lambda2); - } - } - - std::vector lp_initial_solution(lp_model.variables_lower_bounds.size(), 0.0); - for (ItemPos item_var_pos = 0; - item_var_pos < (ItemPos)unfixed_items.size(); - ++item_var_pos) { - ItemPos item_pos = unfixed_items[item_var_pos]; - const SolutionItem& solution_item = solution_bin.items[item_pos]; - lp_initial_solution[x[item_pos]] = solution_item.bl_corner.x * sv; - lp_initial_solution[y[item_pos]] = solution_item.bl_corner.y * sv; - lp_initial_solution[lambda_var[item_pos]] = current_lambda[item_pos]; - } - lp_model.variables_initial_values = lp_initial_solution; - - lp_model.feasibility_tolerance = 1e-6; - lp_model.integrality_tolerance = 1e-10; - - //lp_model.format(std::cout, 4); - //std::cout << lp_model.check_solution(lp_initial_solution, 4) << std::endl; - //std::cout << lp_model.check(4) << std::endl; - - /////////// - // Solve // - /////////// - - //std::cout << "solve" << std::endl; - - std::vector lp_solution; - if (parameters.solver == mathoptsolverscmake::SolverName::Highs) { -#ifdef HIGHS_FOUND - Highs highs; - mathoptsolverscmake::reduce_printout(highs); - mathoptsolverscmake::set_time_limit(highs, parameters.timer.remaining_time()); - highs.setOptionValue("parallel", "off"); - mathoptsolverscmake::load(highs, lp_model); - //mathoptsolverscmake::write_mps(highs, "lp.mps"); - mathoptsolverscmake::solve(highs); - if (highs.getModelStatus() != HighsModelStatus::kOptimal) { - // If the time limit is reached, keep the current solution. - if (parameters.timer.needs_to_end()) - break; - throw std::runtime_error( - FUNC_SIGNATURE + ": LP not solved to optimality; " - "model status: " + highs.modelStatusToString(highs.getModelStatus()) + "."); - } - lp_solution = mathoptsolverscmake::get_solution(highs); -#else - throw std::invalid_argument(FUNC_SIGNATURE); -#endif - } else { - throw std::invalid_argument(FUNC_SIGNATURE); - } - - if (!lp_model.check_solution(lp_solution, 0)) { - throw std::logic_error( - FUNC_SIGNATURE + ": wrong LP solution."); - } - //std::cout << "check " << lp_model.check_solution(lp_solution, 4) << std::endl;; - double new_value = lp_model.evaluate_objective(lp_solution); - - // Compute items_shrunken and lambda values for this LP solution. - std::vector new_items_shrunken(solution_bin.items.size(), false); - std::vector new_lambda(solution_bin.items.size()); - for (ItemPos item_pos = 0; - item_pos < (ItemPos)solution_bin.items.size(); - ++item_pos) { - const SolutionItem& item = solution_bin.items[item_pos]; - new_lambda[item_pos] = (!item.is_fixed)? lp_solution[lambda_var[item_pos]]: 1.0; - new_items_shrunken[item_pos] = new_lambda[item_pos] < 1.0 - 1e-6; - //std::cout << "item_pos " << item_pos - // << " lambda " << new_lambda[item_pos] - // << " shrunken " << new_items_shrunken[item_pos] - // << std::endl; - } - - if (!shape::strictly_greater(new_value, current_value)) - break; - - // Retrieve solution. - SolutionBuilder new_solution_builder(instance); - new_solution_builder.add_bin(solution_bin.bin_type_id, 1); - for (ItemPos pos = 0; pos < (ItemPos)solution_bin.items.size(); ++pos) { - const SolutionItem& solution_item = solution_bin.items[pos]; - if (solution_item.is_fixed) { - new_solution_builder.add_item( - 0, - solution_item.item_type_id, - solution_item.bl_corner, - solution_item.angle, - solution_item.mirror, - true); - } else { - new_solution_builder.add_item( - 0, - solution_item.item_type_id, - {lp_solution[x[pos]] / sv, lp_solution[y[pos]] / sv}, - solution_item.angle, - solution_item.mirror); - } - } - Solution new_solution = new_solution_builder.build(); - - // Check intersections between convex parts. - for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_parts) { - const SolutionBin& bin_prev = solution.bin(bin_pos); - const SolutionBin& bin_curr = new_solution.bin(bin_pos); - ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; - ItemPos item_2_pos = unfixed_items[e.item_2_var_pos]; - const Shape& convex_part_1 = item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape; - const Shape& convex_part_2 = item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape; - Shape convex_part_1_prev = convex_part_1; - Shape convex_part_2_prev = convex_part_2; - Shape convex_part_1_curr = convex_part_1; - Shape convex_part_2_curr = convex_part_2; - convex_part_1_prev = current_lambda[item_1_pos] * convex_part_1_prev; - convex_part_1_curr = new_lambda[item_1_pos] * convex_part_1_curr; - convex_part_2_prev = current_lambda[item_2_pos] * convex_part_2_prev; - convex_part_2_curr = new_lambda[item_2_pos] * convex_part_2_curr; - const SolutionItem& item_1_prev = bin_prev.items[item_1_pos]; - const SolutionItem& item_2_prev = bin_prev.items[item_2_pos]; - const SolutionItem& item_1_curr = bin_curr.items[item_1_pos]; - const SolutionItem& item_2_curr = bin_curr.items[item_2_pos]; - convex_part_1_prev.shift(item_1_prev.bl_corner.x * sv, item_1_prev.bl_corner.y * sv); - convex_part_1_curr.shift(item_1_curr.bl_corner.x * sv, item_1_curr.bl_corner.y * sv); - convex_part_2_prev.shift(item_2_prev.bl_corner.x * sv, item_2_prev.bl_corner.y * sv); - convex_part_2_curr.shift(item_2_curr.bl_corner.x * sv, item_2_curr.bl_corner.y * sv); - if (equal(new_lambda[item_1_pos], 0.0)) { - if (equal(new_lambda[item_2_pos], 0.0)) { - if (!equal(item_1_curr.bl_corner, item_2_curr.bl_corner)) - continue; - } else { - if (!convex_part_2_curr.contains(item_1_curr.bl_corner, true)) - continue; - } - } else { - if (equal(new_lambda[item_2_pos], 0.0)) { - if (!convex_part_1_curr.contains(item_2_curr.bl_corner, true)) - continue; - } else { - if (!intersect(convex_part_1_curr, convex_part_2_curr, true)) - continue; - } - } - - std::string constraint_name - = "sep_i" + std::to_string(e.item_1_var_pos) - + "_s" + std::to_string(e.item_shape_1_pos) - + "_p" + std::to_string(e.item_part_1_pos) - + "_i" + std::to_string(e.item_2_var_pos) - + "_s" + std::to_string(e.item_shape_2_pos) - + "_p" + std::to_string(e.item_part_2_pos); - throw std::logic_error( - FUNC_SIGNATURE + ": convex part intersection after LP; " - "constraint: " + constraint_name + "."); - } - - Solution::OverlappingItems overlapping_items = new_solution.compute_overlapping_items(0, &new_lambda); - if (!overlapping_items.item_item_pairs.empty()) { - throw std::logic_error( - FUNC_SIGNATURE + ": infeasible new_solution after LP."); - } - - solution = new_solution; - current_value = new_value; - current_items_shrunken = new_items_shrunken; - current_lambda = new_lambda; - } - - output.solution = solution; - output.items_shrunken = current_items_shrunken; - output.final_lambda = current_lambda; - output.feasible = std::none_of( - current_items_shrunken.begin(), - current_items_shrunken.end(), - [](bool s) { return s; }); - - return output; -} diff --git a/src/irregular/linear_programming.hpp b/src/irregular/linear_programming.hpp deleted file mode 100644 index 6db59da97..000000000 --- a/src/irregular/linear_programming.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Linear programming - * - * The goal of the linear programming algorithm is to push the items of a given - * solution towards a given corner. - */ - -#pragma once - -#include "packingsolver/irregular/solution.hpp" - -#include "mathoptsolverscmake/mathopt.hpp" - -namespace packingsolver -{ -namespace irregular -{ - - -struct EdgeSeparationConstraintParameters -{ - /** Shape to which the separating line belongs. */ - ShapePos edge_shape_pos = -1; - - /** Separating element. */ - ElementPos edge_element_pos = -1; - - /** Element of the closest point. */ - ElementPos point_element_pos = -1; - - /** Closest point from the separating element. */ - Point point; - - /** Signed distance between the closest element and the separating line. */ - LengthDbl distance; - - /** - * Signed distance with the unscaled point. - * - * Used as tie-breaker when the shape scale is 0.0. - */ - LengthDbl distance_unscaled; - - - LengthDbl coef_x1; - LengthDbl coef_y1; - LengthDbl coef_x2; - LengthDbl coef_y2; - LengthDbl coef_lambda1; - LengthDbl coef_lambda2; -}; - -/** - * Find an edge to separate two given shapes. - * - * The selected edge is the less constraining one. - */ -EdgeSeparationConstraintParameters find_best_edge_separator( - const Shape& shape_1, - const Point& shift_1, - double scale_1, - const Shape& shape_2, - const Point& shift_2, - double scale_2); - -struct LinearProgrammingMinimizeShrinkageOutput -{ - /** Constructor. */ - LinearProgrammingMinimizeShrinkageOutput(const Instance& instance): - solution(instance) { } - - Solution solution; - - /** Boolean indicating if the final solution is feasible (all items at full scale). */ - bool feasible = false; - - /** For each item position, true if the item was scaled below 1 in the final LP. */ - std::vector items_shrunken; - - /** Final lambda value for each item (scale factor in [0, 1]). */ - std::vector final_lambda; - - Counter number_of_iterations = 0; -}; - -struct LinearProgrammingMinimizeShrinkageParameters: packingsolver::Parameters -{ - - /** Linear programming solver. */ - mathoptsolverscmake::SolverName solver - = mathoptsolverscmake::SolverName::Highs; -}; - -LinearProgrammingMinimizeShrinkageOutput linear_programming_minimize_shrinkage( - const Solution& initial_solution, - const std::vector& initial_lambda, - const std::vector& item_penalties, - const LinearProgrammingMinimizeShrinkageParameters& parameters = {}); - - -struct LinearProgrammingAnchorOutput -{ - /** Constructor. */ - LinearProgrammingAnchorOutput(const Instance& instance): - solution(instance) { } - - Solution solution; - - Counter number_of_iterations = 0; -}; - -struct LinearProgrammingAnchorParameters: packingsolver::Parameters -{ - /** Linear programming solver. */ - mathoptsolverscmake::SolverName solver - = mathoptsolverscmake::SolverName::Highs; -}; - -LinearProgrammingAnchorOutput linear_programming_anchor( - const Solution& initial_solution, - double x_weight, - double y_weight, - const LinearProgrammingAnchorParameters& parameters = {}); - -} -} diff --git a/src/irregular/linear_programming/anchor.cpp b/src/irregular/linear_programming/anchor.cpp new file mode 100644 index 000000000..4f54eb104 --- /dev/null +++ b/src/irregular/linear_programming/anchor.cpp @@ -0,0 +1,481 @@ +#include "irregular/linear_programming/anchor.hpp" + +#include "irregular/utils.hpp" +#include "irregular/solution_builder.hpp" + +#ifdef CBC_FOUND +#include "mathoptsolverscmake/mathopt_cbc.hpp" +#endif +#ifdef HIGHS_FOUND +#include "mathoptsolverscmake/mathopt_highs.hpp" +#endif +#ifdef XPRESS_FOUND +#include "mathoptsolverscmake/mathopt_xpress.hpp" +#endif + +using namespace packingsolver; +using namespace packingsolver::irregular; + +namespace +{ + +Solution linear_programming_anchor( + const Instance& instance, + const Solution& initial_solution, + double x_weight, + double y_weight, + const LinearProgrammingAnchorParameters& parameters, + const InstanceBasicShapeDecomposition& icd) +{ + // Check that the solution has a single bin. + if (initial_solution.number_of_bins() != 1) { + throw std::invalid_argument( + FUNC_SIGNATURE); + } + + // Get bin type. + const BinPos bin_pos = 0; + const BinTypeId bin_type_id = initial_solution.bin(bin_pos).bin_type_id; + const BinType& bin_type = instance.bin_type(bin_type_id); + + // Compute fixed and unfixed items. + std::vector fixed_items; + std::vector unfixed_items; + for (ItemPos item_pos = 0; + item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); + ++item_pos) { + const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; + if (solution_item.is_fixed) { + fixed_items.push_back(item_pos); + } else { + unfixed_items.push_back(item_pos); + } + } + + // Precompute rotated convex decompositions for each solution item. + // item_rotated_decompositions[item_pos][item_shape_pos] = list of convex parts + // with the item's angle and mirror already applied. + std::vector>> item_rotated_decompositions(initial_solution.bin(bin_pos).items.size()); + for (ItemPos item_pos = 0; + item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); + ++item_pos) { + const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; + const ItemType& item_type = instance.item_type(solution_item.item_type_id); + item_rotated_decompositions[item_pos].resize(item_type.shapes.size()); + for (ItemShapePos item_shape_pos = 0; + item_shape_pos < (ItemShapePos)item_type.shapes.size(); + ++item_shape_pos) { + for (const BasicShape& basic_shape: icd.item_types[solution_item.item_type_id][item_shape_pos]) { + item_rotated_decompositions[item_pos][item_shape_pos].push_back( + apply_placement(basic_shape, solution_item.mirror, solution_item.angle)); + } + } + } + + // Precompute AABBs for fixed items, border and defect convex parts (fixed world coordinates). + std::vector fixed_item_part_aabbs; + for (ItemPos item_pos = 0; + item_pos < (ItemPos)initial_solution.bin(bin_pos).items.size(); + ++item_pos) { + const SolutionItem& solution_item = initial_solution.bin(bin_pos).items[item_pos]; + if (!solution_item.is_fixed) + continue; + const LengthDbl cx = solution_item.bl_corner.x * instance.parameters().scale_value; + const LengthDbl cy = solution_item.bl_corner.y * instance.parameters().scale_value; + for (ItemShapePos item_shape_pos = 0; + item_shape_pos < (ItemShapePos)item_rotated_decompositions[item_pos].size(); + ++item_shape_pos) { + const auto& parts = item_rotated_decompositions[item_pos][item_shape_pos]; + for (Counter part_pos = 0; part_pos < (Counter)parts.size(); ++part_pos) { + const AxisAlignedBoundingBox p = parts[part_pos].shape.compute_min_max(); + AxisAlignedBoundingBox ps; + ps.x_min = cx + p.x_min; + ps.x_max = cx + p.x_max; + ps.y_min = cy + p.y_min; + ps.y_max = cy + p.y_max; + fixed_item_part_aabbs.push_back(ps); + } + } + } + std::vector border_part_aabbs; + for (const BasicShape& part: icd.bin_types_borders[bin_type_id]) + border_part_aabbs.push_back(part.shape.compute_min_max()); + std::vector defect_part_aabbs; + for (const BasicShape& part: icd.bin_types_defects[bin_type_id]) + defect_part_aabbs.push_back(part.shape.compute_min_max()); + + LengthDbl movement_box_half_size = 10; + + Solution solution = initial_solution; + double current_value = 0; + for (const SolutionItem& solution_item: initial_solution.bin(bin_pos).items) { + current_value += x_weight * solution_item.bl_corner.x * instance.parameters().scale_value; + current_value += y_weight * solution_item.bl_corner.y * instance.parameters().scale_value; + } + // Lambda is fixed at 1 for anchor_to_corner (no shrinkage variables). + const std::vector anchor_lambda(initial_solution.bin(bin_pos).items.size(), 1.0); + + for (Counter number_of_iterations = 0;; ++number_of_iterations) { + const SolutionBin& solution_bin = solution.bin(bin_pos); + + const std::vector unfixed_item_aabbs = compute_unfixed_item_aabbs( + instance, + solution_bin, + movement_box_half_size, + item_rotated_decompositions, + anchor_lambda); + + // Precompute per-item bin bounds (without movement restriction). + // The local bounding box of each item is read from item_aabbs. + std::vector item_bin_bounds(unfixed_items.size()); + for (ItemPos item_var_pos = 0; + item_var_pos < (ItemPos)unfixed_items.size(); + ++item_var_pos) { + const AxisAlignedBoundingBox& ia = unfixed_item_aabbs[item_var_pos].item_aabb; + LengthDbl x_min = (x_weight < 0)? solution.x_min(): bin_type.aabb_orig.x_min; + LengthDbl x_max = (x_weight > 0)? solution.x_max(): bin_type.aabb_orig.x_max; + LengthDbl y_min = (y_weight < 0)? solution.y_min(): bin_type.aabb_orig.y_min; + LengthDbl y_max = (y_weight > 0)? solution.y_max(): bin_type.aabb_orig.y_max; + item_bin_bounds[item_var_pos].x_min = x_min * instance.parameters().scale_value - ia.x_min; + item_bin_bounds[item_var_pos].x_max = x_max * instance.parameters().scale_value - ia.x_max; + item_bin_bounds[item_var_pos].y_min = y_min * instance.parameters().scale_value - ia.y_min; + item_bin_bounds[item_var_pos].y_max = y_max * instance.parameters().scale_value - ia.y_max; + } + + IntersectingParts intersecting_parts = compute_potentially_intersecting_parts( + unfixed_item_aabbs, + fixed_item_part_aabbs, + border_part_aabbs, + defect_part_aabbs); + + //////////////////// + // Setup LP model // + //////////////////// + + // Build LP model. + mathoptsolverscmake::MathOptModel lp_model; + + ///////////////////////////// + // Objective and variables // + ///////////////////////////// + + // Set objective sense. + lp_model.objective_direction = mathoptsolverscmake::ObjectiveDirection::Minimize; + + std::vector x(solution_bin.items.size(), -1); + std::vector y(solution_bin.items.size(), -1); + for (ItemPos item_var_pos = 0; + item_var_pos < (ItemPos)unfixed_items.size(); + ++item_var_pos) { + ItemPos item_pos = unfixed_items[item_var_pos]; + const SolutionItem& solution_item = solution_bin.items[item_pos]; + + x[item_pos] = lp_model.variables_lower_bounds.size(); + lp_model.variables_lower_bounds.push_back(std::max( + item_bin_bounds[item_var_pos].x_min, + solution_item.bl_corner.x * instance.parameters().scale_value - movement_box_half_size)); + lp_model.variables_upper_bounds.push_back(std::min( + item_bin_bounds[item_var_pos].x_max, + solution_item.bl_corner.x * instance.parameters().scale_value +movement_box_half_size)); + lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); + lp_model.objective_coefficients.push_back(x_weight); + lp_model.variables_names.push_back("x_" + std::to_string(item_pos)); + + y[item_pos] = lp_model.variables_lower_bounds.size(); + lp_model.variables_lower_bounds.push_back(std::max( + item_bin_bounds[item_var_pos].y_min, + solution_item.bl_corner.y * instance.parameters().scale_value - movement_box_half_size)); + lp_model.variables_upper_bounds.push_back(std::min( + item_bin_bounds[item_var_pos].y_max, + solution_item.bl_corner.y * instance.parameters().scale_value + movement_box_half_size)); + lp_model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); + lp_model.objective_coefficients.push_back(y_weight); + lp_model.variables_names.push_back("y_" + std::to_string(item_pos)); + } + + ///////////////// + // Constraints // + ///////////////// + + // Obstacle (shape_1) is at world origin with scale=1 (fixed). + // Item (shape_2) has LP variables x, y at scale=1 (no lambda in atc). + // Full constraint: coef_x1*0 + coef_y1*0 + coef_lambda1 + coef_x2*x + coef_y2*y + coef_lambda2 >= 0 + // => coef_x2*x + coef_y2*y >= -(coef_lambda1 + coef_lambda2) + + const LengthDbl sv = instance.parameters().scale_value; + + // Intersections between an unifxed item and a fixed item. + for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_part_fixed_item_part) { + ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; + ItemPos item_2_pos = fixed_items[e.item_2_var_pos]; + const SolutionItem& item_1 = solution_bin.items[item_1_pos]; + const SolutionItem& item_2 = solution_bin.items[item_2_pos]; + const EdgeSeparationConstraintParameters p = find_best_edge_separator( + item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape, + sv * item_1.bl_corner, + 1.0, + item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape, + sv * item_2.bl_corner, + 1.0); + if (shape::equal(p.coef_x1, 0.0) && shape::equal(p.coef_y1, 0.0)) + continue; + lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); + lp_model.constraints_names.push_back( + "sep_fixed_i_" + std::to_string(item_1_pos) + + "_s" + std::to_string(e.item_shape_1_pos) + + "_p" + std::to_string(e.item_part_1_pos) + + "_i" + std::to_string(item_2_pos) + + "_s" + std::to_string(e.item_shape_2_pos) + + "_p" + std::to_string(e.item_part_2_pos)); + lp_model.constraints_lower_bounds.push_back( + -p.coef_x2 * item_2.bl_corner.x * sv + -p.coef_y2 * item_2.bl_corner.y * sv + -p.coef_lambda2 + -p.coef_lambda1); + lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); + if (!shape::equal(p.coef_x1, 0.0)) { + lp_model.elements_variables.push_back(x[item_1_pos]); + lp_model.elements_coefficients.push_back(p.coef_x1); + } + if (!shape::equal(p.coef_y1, 0.0)) { + lp_model.elements_variables.push_back(y[item_1_pos]); + lp_model.elements_coefficients.push_back(p.coef_y1); + } + } + + // Intersections between items and bin borders. + for (const IntersectingItemPartDefectPart& e: intersecting_parts.intersecting_item_part_border_part) { + ItemPos item_pos = unfixed_items[e.item_var_pos]; + const SolutionItem& item = solution_bin.items[item_pos]; + const EdgeSeparationConstraintParameters p = find_best_edge_separator( + item_rotated_decompositions[item_pos][e.item_shape_pos][e.item_part_pos].shape, + sv * item.bl_corner, + 1.0, + icd.bin_types_borders[bin_type_id][e.defect_pos].shape, + Point{0, 0}, + 1.0); + if (shape::equal(p.coef_x1, 0.0) && shape::equal(p.coef_y1, 0.0)) + continue; + lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); + lp_model.constraints_names.push_back( + "border_i" + std::to_string(item_pos) + + "_s" + std::to_string(e.item_shape_pos) + + "_p" + std::to_string(e.item_part_pos) + + "_bp" + std::to_string(e.defect_pos)); + lp_model.constraints_lower_bounds.push_back(-p.coef_lambda2 - p.coef_lambda1); + lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); + if (!shape::equal(p.coef_x1, 0.0)) { + lp_model.elements_variables.push_back(x[item_pos]); + lp_model.elements_coefficients.push_back(p.coef_x1); + } + if (!shape::equal(p.coef_y1, 0.0)) { + lp_model.elements_variables.push_back(y[item_pos]); + lp_model.elements_coefficients.push_back(p.coef_y1); + } + } + + // Intersections between items and bin defects. + for (const IntersectingItemPartDefectPart& e: intersecting_parts.intersecting_item_part_defect_part) { + ItemPos item_pos = unfixed_items[e.item_var_pos]; + const SolutionItem& item = solution_bin.items[item_pos]; + const EdgeSeparationConstraintParameters p = find_best_edge_separator( + item_rotated_decompositions[item_pos][e.item_shape_pos][e.item_part_pos].shape, + sv * item.bl_corner, + 1.0, + icd.bin_types_defects[bin_type_id][e.defect_pos].shape, + Point{0, 0}, + 1.0); + if (shape::equal(p.coef_x1, 0.0) && shape::equal(p.coef_y1, 0.0)) + continue; + lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); + lp_model.constraints_names.push_back( + "defect_i" + std::to_string(e.item_var_pos) + + "_s" + std::to_string(e.item_shape_pos) + + "_p" + std::to_string(e.item_part_pos) + + "_dp" + std::to_string(e.defect_pos)); + lp_model.constraints_lower_bounds.push_back(-p.coef_lambda2 - p.coef_lambda1); + lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); + if (!shape::equal(p.coef_x1, 0.0)) { + lp_model.elements_variables.push_back(x[item_pos]); + lp_model.elements_coefficients.push_back(p.coef_x1); + } + if (!shape::equal(p.coef_y1, 0.0)) { + lp_model.elements_variables.push_back(y[item_pos]); + lp_model.elements_coefficients.push_back(p.coef_y1); + } + } + + // Intersections between pairs of items. + // Full constraint: coef_x1*x1 + coef_y1*y1 + coef_lambda1 + coef_x2*x2 + coef_y2*y2 + coef_lambda2 >= 0 + // => coef_x1*x1 + coef_y1*y1 + coef_x2*x2 + coef_y2*y2 >= -(coef_lambda1 + coef_lambda2) + for (const IntersectingItemParts& e: intersecting_parts.intersecting_item_parts) { + ItemPos item_1_pos = unfixed_items[e.item_1_var_pos]; + ItemPos item_2_pos = unfixed_items[e.item_2_var_pos]; + const SolutionItem& item_1 = solution_bin.items[item_1_pos]; + const SolutionItem& item_2 = solution_bin.items[item_2_pos]; + const Shape& convex_part_1 = item_rotated_decompositions[item_1_pos][e.item_shape_1_pos][e.item_part_1_pos].shape; + const Shape& convex_part_2 = item_rotated_decompositions[item_2_pos][e.item_shape_2_pos][e.item_part_2_pos].shape; + const EdgeSeparationConstraintParameters p = find_best_edge_separator( + convex_part_1, + sv * item_1.bl_corner, + 1.0, // scale + convex_part_2, + sv * item_2.bl_corner, + 1.0); // scale + lp_model.constraints_starts.push_back(lp_model.elements_variables.size()); + lp_model.constraints_names.push_back( + "sep_i" + std::to_string(e.item_1_var_pos) + + "_s" + std::to_string(e.item_shape_1_pos) + + "_p" + std::to_string(e.item_part_1_pos) + + "_i" + std::to_string(e.item_2_var_pos) + + "_s" + std::to_string(e.item_shape_2_pos) + + "_p" + std::to_string(e.item_part_2_pos)); + lp_model.constraints_lower_bounds.push_back(-(p.coef_lambda1 + p.coef_lambda2)); + lp_model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); + if (!shape::equal(p.coef_x1, 0.0)) { + lp_model.elements_variables.push_back(x[item_1_pos]); + lp_model.elements_coefficients.push_back(p.coef_x1); + } + if (!shape::equal(p.coef_y1, 0.0)) { + lp_model.elements_variables.push_back(y[item_1_pos]); + lp_model.elements_coefficients.push_back(p.coef_y1); + } + if (!shape::equal(p.coef_x2, 0.0)) { + lp_model.elements_variables.push_back(x[item_2_pos]); + lp_model.elements_coefficients.push_back(p.coef_x2); + } + if (!shape::equal(p.coef_y2, 0.0)) { + lp_model.elements_variables.push_back(y[item_2_pos]); + lp_model.elements_coefficients.push_back(p.coef_y2); + } + } + + //lp_model.feasiblity_tolerance = 1e-3; + //lp_model.check(1); + //lp_model.format(std::cout, 4); + + std::vector lp_initial_solution(lp_model.variables_lower_bounds.size()); + for (ItemPos item_var_pos = 0; + item_var_pos < (ItemPos)unfixed_items.size(); + ++item_var_pos) { + ItemPos item_pos = unfixed_items[item_var_pos]; + const SolutionItem& solution_item = solution_bin.items[item_pos]; + lp_initial_solution[x[item_pos]] = solution_item.bl_corner.x * sv; + lp_initial_solution[y[item_pos]] = solution_item.bl_corner.y * sv; + } + lp_model.variables_initial_values = lp_initial_solution; + //lp_model.format_solution(std::cout, lp_initial_solution, 4); + //lp_model.check_solution(lp_initial_solution, 1); + + /////////// + // Solve // + /////////// + + std::vector lp_solution; + if (parameters.solver == mathoptsolverscmake::SolverName::Highs) { +#ifdef HIGHS_FOUND + Highs highs; + mathoptsolverscmake::reduce_printout(highs); + mathoptsolverscmake::set_time_limit(highs, parameters.timer.remaining_time()); + highs.setOptionValue("parallel", "off"); + //mathoptsolverscmake::set_log_file(highs, "highs.log"); + mathoptsolverscmake::load(highs, lp_model); + //std::cout << "LP solve start" << std::endl; + mathoptsolverscmake::solve(highs); + //std::cout << "LP solve end" << std::endl; + if (highs.getModelStatus() != HighsModelStatus::kOptimal) { + // If the time limit is reached, keep the current solution. + if (parameters.timer.needs_to_end()) + break; + throw std::runtime_error( + FUNC_SIGNATURE + ": LP not solved to optimality; " + "model status: " + highs.modelStatusToString(highs.getModelStatus()) + "."); + } + lp_solution = mathoptsolverscmake::get_solution(highs); +#else + throw std::invalid_argument(FUNC_SIGNATURE); +#endif + + } else { + throw std::invalid_argument(FUNC_SIGNATURE); + } + + double new_value = lp_model.evaluate_objective(lp_solution); + + // If the solution of the MILP model is not better, stop. + if (!shape::strictly_greater(current_value, new_value)) + break; + current_value = new_value; + + // Retrieve solution. + SolutionBuilder new_solution_builder(instance); + new_solution_builder.add_bin(solution_bin.bin_type_id, 1); + for (ItemPos pos = 0; pos < (ItemPos)solution_bin.items.size(); ++pos) { + const SolutionItem& solution_item = solution_bin.items[pos]; + if (solution_item.is_fixed) { + new_solution_builder.add_item( + 0, + solution_item.item_type_id, + solution_item.bl_corner, + solution_item.angle, + solution_item.mirror, + true); + } else { + new_solution_builder.add_item( + 0, + solution_item.item_type_id, + {lp_solution[x[pos]] / instance.parameters().scale_value, lp_solution[y[pos]] / instance.parameters().scale_value}, + solution_item.angle, + solution_item.mirror); + } + } + solution = new_solution_builder.build(); + } + + return solution; +} + +} + +LinearProgrammingAnchorOutput packingsolver::irregular::linear_programming_anchor( + const Solution& initial_solution, + double x_weight, + double y_weight, + const LinearProgrammingAnchorParameters& parameters) +{ + //std::cout << "linear_programming" << std::endl; + const Instance& instance = initial_solution.instance(); + LinearProgrammingAnchorOutput output(instance); + + const InstanceBasicShapeDecomposition icd = compute_instance_basic_shape_decomposition(instance); + + Solution solution(instance); + for (BinPos bin_pos = 0; + bin_pos < initial_solution.number_of_different_bins(); + ++bin_pos) { + const SolutionBin& solution_bin = initial_solution.bin(bin_pos); + Solution initial_solution_cur(instance); + initial_solution_cur.append_bin(initial_solution, bin_pos, 1); + Solution new_solution_cur = ::linear_programming_anchor( + instance, + initial_solution_cur, + x_weight, + y_weight, + parameters, + icd); + solution.append_bin( + new_solution_cur, + 0, + solution_bin.copies); + } + //initial_solution.format(std::cout, 1); + //solution.format(std::cout, 1); + output.solution = solution; + + //instance.write("lp_test.json"); + //initial_solution.write("lp_test_initial.json"); + //solution.write("lp_test_expected.json"); + //exit(1); + //std::cout << "linear_programming end" << std::endl; + return output; +} diff --git a/src/irregular/linear_programming/anchor.hpp b/src/irregular/linear_programming/anchor.hpp new file mode 100644 index 000000000..3c5d30c1d --- /dev/null +++ b/src/irregular/linear_programming/anchor.hpp @@ -0,0 +1,44 @@ +/** + * Linear programming anchor + * + * The goal of the linear programming anchor algorithm is to push the items of + * a given solution towards a given corner. + */ + +#pragma once + +#include "packingsolver/irregular/solution.hpp" + +#include "mathoptsolverscmake/mathopt.hpp" + +namespace packingsolver +{ +namespace irregular +{ + +struct LinearProgrammingAnchorOutput +{ + /** Constructor. */ + LinearProgrammingAnchorOutput(const Instance& instance): + solution(instance) { } + + Solution solution; + + Counter number_of_iterations = 0; +}; + +struct LinearProgrammingAnchorParameters: packingsolver::Parameters +{ + /** Linear programming solver. */ + mathoptsolverscmake::SolverName solver + = mathoptsolverscmake::SolverName::Highs; +}; + +LinearProgrammingAnchorOutput linear_programming_anchor( + const Solution& initial_solution, + double x_weight, + double y_weight, + const LinearProgrammingAnchorParameters& parameters = {}); + +} +} diff --git a/src/irregular/linear_programming/separation_model.cpp b/src/irregular/linear_programming/separation_model.cpp new file mode 100644 index 000000000..a14f4f493 --- /dev/null +++ b/src/irregular/linear_programming/separation_model.cpp @@ -0,0 +1,456 @@ +#include "irregular/linear_programming/separation_model.hpp" + +#include "irregular/utils.hpp" + +#include "mathoptsolverscmake/mathopt.hpp" +#ifdef HIGHS_FOUND +#include "mathoptsolverscmake/mathopt_highs.hpp" +#endif + +#include +#include +#include + +using namespace packingsolver; +using namespace packingsolver::irregular; + +BinSeparationModel::BinSeparationModel( + const Instance& instance, + const InstanceBasicShapeDecomposition& decomposition, + BinTypeId bin_type_id, + const std::vector& items): + instance_(instance), + bin_type_id_(bin_type_id) +{ + const BinType& bin_type = instance.bin_type(bin_type_id); + const LengthDbl scale_value = instance.parameters().scale_value; + item_spacing_ = instance.item_spacing_scaled(); + bin_spacing_ = instance.bin_spacing_scaled(bin_type_id); + maximum_spacing_ = (std::max)(item_spacing_, bin_spacing_); + + auto add_part = [this]( + ItemPos item_pos, + const Shape& shape, + const Point& shift, + LengthDbl spacing) + { + Part part; + part.item_pos = item_pos; + part.spacing = spacing; + for (const ShapeElement& element: shape.elements) { + Point vertex = {element.start.x + shift.x, element.start.y + shift.y}; + part.vertices.push_back(vertex); + part.aabb.x_min = (std::min)(part.aabb.x_min, vertex.x); + part.aabb.x_max = (std::max)(part.aabb.x_max, vertex.x); + part.aabb.y_min = (std::min)(part.aabb.y_min, vertex.y); + part.aabb.y_max = (std::max)(part.aabb.y_max, vertex.y); + } + parts_.push_back(part); + return part.aabb; + }; + + const Point origin = {0.0, 0.0}; + items_aabbs_.resize(items.size()); + for (ItemPos item_pos = 0; item_pos < (ItemPos)items.size(); ++item_pos) { + const SeparationModelItem& item = items[item_pos]; + const ItemType& item_type = instance.item_type(item.item_type_id); + for (ItemShapePos item_shape_pos = 0; + item_shape_pos < (ItemShapePos)item_type.shapes.size(); + ++item_shape_pos) { + for (const BasicShape& basic_shape: decomposition.item_types[item.item_type_id][item_shape_pos]) { + if (basic_shape.type != BasicShapeType::ConvexPolygon + || !basic_shape.shape.is_polygon()) { + supported_ = false; + return; + } + BasicShape placed_shape = apply_placement(basic_shape, item.mirror, item.angle); + if (item.is_fixed) { + add_part(-1, placed_shape.shape, item.position, item_spacing_); + } else { + items_aabbs_[item_pos] = merge( + items_aabbs_[item_pos], + add_part(item_pos, placed_shape.shape, origin, 0.0)); + } + } + } + } + for (const BasicShape& basic_shape: decomposition.bin_types_borders[bin_type_id]) { + if (!basic_shape.shape.is_polygon()) { + supported_ = false; + return; + } + add_part(-1, basic_shape.shape, origin, bin_spacing_); + } + // The defect of each part of the decomposition of the defects isn't + // known: use the largest item-defect spacing of the bin. + LengthDbl defect_spacing = 0.0; + for (const auto& defect: bin_type.defects) + defect_spacing = (std::max)(defect_spacing, scale_value * defect.item_defect_minimum_spacing); + maximum_spacing_ = (std::max)(maximum_spacing_, defect_spacing); + for (const BasicShape& basic_shape: decomposition.bin_types_defects[bin_type_id]) { + if (!basic_shape.shape.is_polygon()) { + supported_ = false; + return; + } + add_part(-1, basic_shape.shape, origin, defect_spacing); + } +} + +AxisAlignedBoundingBox BinSeparationModel::part_aabb( + const std::vector& items, + Counter part_pos) const +{ + const Part& part = parts_[part_pos]; + if (part.item_pos == -1) + return part.aabb; + const SeparationModelItem& item = items[part.item_pos]; + AxisAlignedBoundingBox aabb; + aabb.x_min = item.position.x + item.lambda * part.aabb.x_min; + aabb.x_max = item.position.x + item.lambda * part.aabb.x_max; + aabb.y_min = item.position.y + item.lambda * part.aabb.y_min; + aabb.y_max = item.position.y + item.lambda * part.aabb.y_max; + return aabb; +} + +LengthDbl BinSeparationModel::value( + const std::vector& items, + const Constraint& constraint) const +{ + ItemPos edge_item_pos = parts_[constraint.edge_part_pos].item_pos; + ItemPos support_item_pos = parts_[constraint.support_part_pos].item_pos; + Point edge_position = {0.0, 0.0}; + Point support_position = {0.0, 0.0}; + double edge_lambda = 1.0; + double support_lambda = 1.0; + if (edge_item_pos != -1) { + edge_position = items[edge_item_pos].position; + edge_lambda = items[edge_item_pos].lambda; + } + if (support_item_pos != -1) { + support_position = items[support_item_pos].position; + support_lambda = items[support_item_pos].lambda; + } + return constraint.normal.x * (support_position.x - edge_position.x) + + constraint.normal.y * (support_position.y - edge_position.y) + + constraint.support_coefficient * support_lambda + - constraint.edge_coefficient * edge_lambda + - constraint.spacing; +} + +BinSeparationModel::Constraint BinSeparationModel::best_constraint( + const std::vector& items, + Counter part_pos_1, + Counter part_pos_2, + LengthDbl& best_value) const +{ + const LengthDbl infinity = std::numeric_limits::infinity(); + const Part& part_1 = parts_[part_pos_1]; + const Part& part_2 = parts_[part_pos_2]; + + // Best separating edge, among the edges of both parts. + Constraint best_constraint; + best_value = -infinity; + for (int side = 0; side < 2; ++side) { + Counter edge_part_pos = (side == 0)? part_pos_1: part_pos_2; + Counter support_part_pos = (side == 0)? part_pos_2: part_pos_1; + const Part& edge_part = parts_[edge_part_pos]; + const Part& support_part = parts_[support_part_pos]; + ElementPos number_of_vertices = edge_part.vertices.size(); + for (ElementPos vertex_pos = 0; vertex_pos < number_of_vertices; ++vertex_pos) { + const Point& edge_start = edge_part.vertices[vertex_pos]; + const Point& edge_end = edge_part.vertices[(vertex_pos + 1) % number_of_vertices]; + LengthDbl delta_x = edge_end.x - edge_start.x; + LengthDbl delta_y = edge_end.y - edge_start.y; + LengthDbl length = std::sqrt(delta_x * delta_x + delta_y * delta_y); + if (length == 0.0) + continue; + Constraint constraint; + constraint.edge_part_pos = edge_part_pos; + constraint.support_part_pos = support_part_pos; + // The parts are anticlockwise: the outward normal is on the right + // of the edge. + constraint.normal = {delta_y / length, -delta_x / length}; + constraint.edge_coefficient = constraint.normal.x * edge_start.x + + constraint.normal.y * edge_start.y; + constraint.support_coefficient = infinity; + for (const Point& vertex: support_part.vertices) { + constraint.support_coefficient = (std::min)( + constraint.support_coefficient, + constraint.normal.x * vertex.x + constraint.normal.y * vertex.y); + } + constraint.spacing = (part_1.item_pos == -1)? part_1.spacing: + (part_2.item_pos == -1)? part_2.spacing: item_spacing_; + LengthDbl value_cur = value(items, constraint); + if (value_cur > best_value) { + best_value = value_cur; + best_constraint = constraint; + } + } + } + return best_constraint; +} + +LengthDbl BinSeparationModel::compute_constraints( + const std::vector& items, + const std::vector& movements, + std::vector& constraints) const +{ + const LengthDbl infinity = std::numeric_limits::infinity(); + constraints.clear(); + + // Boxes of the parts, those of the items expanded by their maximum move + // (at full scale) and the spacing. + std::vector boxes(parts_.size()); + std::vector sorted_parts(parts_.size()); + for (Counter part_pos = 0; part_pos < (Counter)parts_.size(); ++part_pos) { + const Part& part = parts_[part_pos]; + AxisAlignedBoundingBox box = part.aabb; + if (part.item_pos != -1) { + const SeparationModelItem& item = items[part.item_pos]; + LengthDbl expansion = movements[part.item_pos] + maximum_spacing_; + box.x_min = item.position.x + (std::min)(0.0, part.aabb.x_min) - expansion; + box.x_max = item.position.x + (std::max)(0.0, part.aabb.x_max) + expansion; + box.y_min = item.position.y + (std::min)(0.0, part.aabb.y_min) - expansion; + box.y_max = item.position.y + (std::max)(0.0, part.aabb.y_max) + expansion; + } + boxes[part_pos] = box; + sorted_parts[part_pos] = part_pos; + } + std::sort( + sorted_parts.begin(), + sorted_parts.end(), + [&boxes](Counter part_pos_1, Counter part_pos_2) + { + return boxes[part_pos_1].x_min < boxes[part_pos_2].x_min; + }); + + LengthDbl separation = infinity; + for (Counter sorted_pos_1 = 0; sorted_pos_1 < (Counter)sorted_parts.size(); ++sorted_pos_1) { + Counter part_pos_1 = sorted_parts[sorted_pos_1]; + for (Counter sorted_pos_2 = sorted_pos_1 + 1; + sorted_pos_2 < (Counter)sorted_parts.size() + && boxes[sorted_parts[sorted_pos_2]].x_min <= boxes[part_pos_1].x_max; + ++sorted_pos_2) { + Counter part_pos_2 = sorted_parts[sorted_pos_2]; + const Part& part_1 = parts_[part_pos_1]; + const Part& part_2 = parts_[part_pos_2]; + if (part_1.item_pos == -1 && part_2.item_pos == -1) + continue; + if (part_1.item_pos == part_2.item_pos) + continue; + if (boxes[part_pos_2].y_min > boxes[part_pos_1].y_max + || boxes[part_pos_1].y_min > boxes[part_pos_2].y_max) { + continue; + } + + LengthDbl best_value = -infinity; + constraints.push_back(best_constraint(items, part_pos_1, part_pos_2, best_value)); + separation = (std::min)(separation, best_value); + } + } + + // Containment in the bounding box of the bin. + const BinType& bin_type = instance_.bin_type(bin_type_id_); + for (ItemPos item_pos = 0; item_pos < (ItemPos)items.size(); ++item_pos) { + const SeparationModelItem& item = items[item_pos]; + if (item.is_fixed) + continue; + const AxisAlignedBoundingBox& aabb = items_aabbs_[item_pos]; + separation = (std::min)(separation, + item.position.x + item.lambda * aabb.x_min - (bin_type.aabb_scaled.x_min + bin_spacing_)); + separation = (std::min)(separation, + bin_type.aabb_scaled.x_max - bin_spacing_ - (item.position.x + item.lambda * aabb.x_max)); + separation = (std::min)(separation, + item.position.y + item.lambda * aabb.y_min - (bin_type.aabb_scaled.y_min + bin_spacing_)); + separation = (std::min)(separation, + bin_type.aabb_scaled.y_max - bin_spacing_ - (item.position.y + item.lambda * aabb.y_max)); + } + return separation; +} + +LengthDbl BinSeparationModel::separation( + const std::vector& items) const +{ + std::vector movements(items.size(), 0.0); + std::vector constraints; + return compute_constraints(items, movements, constraints); +} + +bool BinSeparationModel::step( + std::vector& items, + const StepParameters& parameters, + const optimizationtools::Timer& timer) const +{ + const LengthDbl infinity = std::numeric_limits::infinity(); + const BinType& bin_type = instance_.bin_type(bin_type_id_); + ItemPos number_of_items = items.size(); + + // Maximum move of each item. + std::vector movements(number_of_items, 0.0); + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + if (items[item_pos].is_fixed) + continue; + const AxisAlignedBoundingBox& aabb = items_aabbs_[item_pos]; + movements[item_pos] = parameters.movement_ratio + * (std::max)(aabb.x_max - aabb.x_min, aabb.y_max - aabb.y_min); + } + std::vector constraints; + compute_constraints(items, movements, constraints); + + // Variables. + mathoptsolverscmake::MathOptModel model; + model.objective_direction = mathoptsolverscmake::ObjectiveDirection::Maximize; + auto add_variable = [&model](double lower_bound, double upper_bound, double objective_coefficient) + { + int variable_id = model.variables_lower_bounds.size(); + model.variables_lower_bounds.push_back(lower_bound); + model.variables_upper_bounds.push_back(upper_bound); + model.variables_types.push_back(mathoptsolverscmake::VariableType::Continuous); + model.objective_coefficients.push_back(objective_coefficient); + return variable_id; + }; + std::vector x(number_of_items, -1); + std::vector y(number_of_items, -1); + std::vector lambda(number_of_items, -1); + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + const SeparationModelItem& item = items[item_pos]; + if (item.is_fixed) + continue; + x[item_pos] = add_variable( + item.position.x - movements[item_pos], + item.position.x + movements[item_pos], + 0.0); + y[item_pos] = add_variable( + item.position.y - movements[item_pos], + item.position.y + movements[item_pos], + 0.0); + if (parameters.shrink) + lambda[item_pos] = add_variable(0.0, 1.0, item.weight); + } + int eta = add_variable(-infinity, parameters.target_separation, parameters.eta_weight); + + // Terms of an item in a row: position and, if variable, scale; the + // constant part of the scale goes to the lower bound. + struct Row + { + std::vector variables; + std::vector coefficients; + double lower_bound = 0.0; + }; + auto add_item_terms = [&items, &x, &y, &lambda]( + Row& row, + ItemPos item_pos, + const Point& normal, + double lambda_coefficient, + double sign) + { + if (item_pos == -1) { + row.lower_bound -= sign * lambda_coefficient; + return; + } + row.variables.push_back(x[item_pos]); + row.coefficients.push_back(sign * normal.x); + row.variables.push_back(y[item_pos]); + row.coefficients.push_back(sign * normal.y); + if (lambda[item_pos] != -1) { + row.variables.push_back(lambda[item_pos]); + row.coefficients.push_back(sign * lambda_coefficient); + } else { + row.lower_bound -= sign * lambda_coefficient * items[item_pos].lambda; + } + }; + auto add_row = [&model, eta](Row& row) + { + model.constraints_starts.push_back(model.elements_variables.size()); + model.constraints_lower_bounds.push_back(row.lower_bound); + model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); + for (Counter pos = 0; pos < (Counter)row.variables.size(); ++pos) { + model.elements_variables.push_back(row.variables[pos]); + model.elements_coefficients.push_back(row.coefficients[pos]); + } + model.elements_variables.push_back(eta); + model.elements_coefficients.push_back(-1.0); + }; + + // normal . (p_support - p_edge) + support_coefficient * lambda_support + // - edge_coefficient * lambda_edge - eta >= spacing. + for (const Constraint& constraint: constraints) { + Row row; + row.lower_bound = constraint.spacing; + add_item_terms( + row, + parts_[constraint.support_part_pos].item_pos, + constraint.normal, + constraint.support_coefficient, + 1.0); + add_item_terms( + row, + parts_[constraint.edge_part_pos].item_pos, + constraint.normal, + constraint.edge_coefficient, + -1.0); + add_row(row); + } + + // Containment: x + lambda * x_min - eta >= bin_x_min + spacing, etc. + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + const SeparationModelItem& item = items[item_pos]; + if (item.is_fixed) + continue; + const AxisAlignedBoundingBox& aabb = items_aabbs_[item_pos]; + const int position_variables[4] = {x[item_pos], x[item_pos], y[item_pos], y[item_pos]}; + const double signs[4] = {1.0, -1.0, 1.0, -1.0}; + const double extents[4] = {aabb.x_min, aabb.x_max, aabb.y_min, aabb.y_max}; + const double limits[4] = { + bin_type.aabb_scaled.x_min + bin_spacing_, + -(bin_type.aabb_scaled.x_max - bin_spacing_), + bin_type.aabb_scaled.y_min + bin_spacing_, + -(bin_type.aabb_scaled.y_max - bin_spacing_)}; + for (int side = 0; side < 4; ++side) { + Row row; + row.lower_bound = limits[side]; + row.variables.push_back(position_variables[side]); + row.coefficients.push_back(signs[side]); + if (lambda[item_pos] != -1) { + row.variables.push_back(lambda[item_pos]); + row.coefficients.push_back(signs[side] * extents[side]); + } else { + row.lower_bound -= signs[side] * extents[side] * item.lambda; + } + add_row(row); + } + } + model.feasibility_tolerance = 1e-9; + + // Solve. No initial solution is given to the solver (see + // https://github.com/ERGO-Code/HiGHS/issues/3454). + std::vector solution; +#ifdef HIGHS_FOUND + Highs highs; + mathoptsolverscmake::reduce_printout(highs); + mathoptsolverscmake::set_time_limit(highs, timer.remaining_time()); + highs.setOptionValue("parallel", "off"); + mathoptsolverscmake::load(highs, model); + mathoptsolverscmake::solve(highs); + if (highs.getModelStatus() != HighsModelStatus::kOptimal) + return false; + solution = mathoptsolverscmake::get_solution(highs); +#else + (void)timer; + throw std::invalid_argument(FUNC_SIGNATURE + ": HiGHS not available."); +#endif + + // New positions and scales, clamped to their bounds. + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + SeparationModelItem& item = items[item_pos]; + if (item.is_fixed) + continue; + item.position.x = (std::max)(item.position.x - movements[item_pos], + (std::min)(item.position.x + movements[item_pos], solution[x[item_pos]])); + item.position.y = (std::max)(item.position.y - movements[item_pos], + (std::min)(item.position.y + movements[item_pos], solution[y[item_pos]])); + if (lambda[item_pos] != -1) + item.lambda = (std::max)(0.0, (std::min)(1.0, solution[lambda[item_pos]])); + } + return true; +} diff --git a/src/irregular/linear_programming/separation_model.hpp b/src/irregular/linear_programming/separation_model.hpp new file mode 100644 index 000000000..41193a5f0 --- /dev/null +++ b/src/irregular/linear_programming/separation_model.hpp @@ -0,0 +1,230 @@ +/** + * Separation model of the items of a bin, solved by linear programming. + * + * The items are decomposed into convex parts, and may be shrunk: an item + * with scale 'lambda' is its shape scaled by 'lambda' around its reference + * point. + * + * For each pair of convex parts close to each other, the edge of one of them + * which separates them the best in the current state is selected; the + * constraint is that the signed distance from the line through this edge to + * the vertex of the other part the closest to it is at least eta (plus the + * minimum spacing). For a fixed edge, this vertex doesn't depend on the + * translations and the scales of the parts, so the constraint is linear in + * the positions and the scales, and a non-negative value proves that the two + * parts don't overlap. + * + * A step solves the linear program maximizing eta first, then the weighted + * sum of the scales (if the items may be shrunk), the items staying in a + * small box around their current positions. + */ + +#pragma once + +#include "packingsolver/irregular/instance.hpp" + +#include "optimizationtools/utils/timer.hpp" + +namespace packingsolver +{ +namespace irregular +{ + +struct InstanceBasicShapeDecomposition; + +/** Item of a bin in the separation model. */ +struct SeparationModelItem +{ + /** Item type. */ + ItemTypeId item_type_id = -1; + + /** Angle. */ + Angle angle = 0.0; + + /** Mirror. */ + bool mirror = false; + + /** True iff the item is fixed: it doesn't move and isn't shrunk. */ + bool is_fixed = false; + + /** Position of the reference point, in scaled coordinates. */ + Point position = {0.0, 0.0}; + + /** Scale. */ + double lambda = 1.0; + + /** Weight of the scale in the objective. */ + double weight = 1.0; +}; + +class BinSeparationModel +{ + +public: + + /** Parameters of a step. */ + struct StepParameters + { + /** + * Maximum move of an item, in each direction, relatively to the + * largest side of its bounding box. + */ + double movement_ratio = 0.05; + + /** True iff the scales of the items are variables. */ + bool shrink = false; + + /** + * Upper bound of eta, in scaled coordinates: a small positive value, + * so that the solution stays feasible despite the tolerances of the + * solver. + */ + LengthDbl target_separation = 1e-5; + + /** Weight of eta in the objective. */ + double eta_weight = 1.0; + }; + + /** + * Constructor. + * + * 'items' gives the item types, the orientations, the fixed items and + * their positions; the positions of the other items and the scales + * aren't used. + */ + BinSeparationModel( + const Instance& instance, + const InstanceBasicShapeDecomposition& decomposition, + BinTypeId bin_type_id, + const std::vector& items); + + /** + * Return true iff the model supports the items: their shapes, the shapes + * of the borders and of the defects are made of line segments. + */ + bool supported() const { return supported_; } + + /** + * Get the smallest separation of the items in a state, in scaled + * coordinates (negative: the largest penetration). + */ + LengthDbl separation(const std::vector& items) const; + + /** + * Solve the linear program of a step, and update the positions and the + * scales of the items. + * + * Return false if the linear program hasn't been solved. + */ + bool step( + std::vector& items, + const StepParameters& parameters, + const optimizationtools::Timer& timer) const; + +private: + + /** Convex part of an item or of an obstacle. */ + struct Part + { + /** + * Position of the item in the bin, or -1 for the parts of the + * obstacles (fixed items, borders and defects). + */ + ItemPos item_pos = -1; + + /** + * Vertices, anticlockwise: relatively to the reference point of the + * item, at full scale, for the parts of the items; in the frame of + * the bin for the parts of the obstacles. + */ + std::vector vertices; + + /** Bounding box, in the same frame as the vertices. */ + AxisAlignedBoundingBox aabb; + + /** + * Minimum spacing between this part and the parts of the items (for + * an obstacle). + */ + LengthDbl spacing = 0.0; + }; + + /** + * Separation constraint of two parts: + * normal . (p_support - p_edge) + * + support_coefficient * lambda_support - edge_coefficient * lambda_edge + * >= spacing. + */ + struct Constraint + { + Counter edge_part_pos = -1; + + Counter support_part_pos = -1; + + Point normal = {0, 0}; + + LengthDbl edge_coefficient = 0.0; + + LengthDbl support_coefficient = 0.0; + + LengthDbl spacing = 0.0; + }; + + /** Bounding box of a part in a state. */ + AxisAlignedBoundingBox part_aabb( + const std::vector& items, + Counter part_pos) const; + + /** + * Constraint of the edge which separates two parts the best in a state; + * 'best_value' is set to its value. + */ + Constraint best_constraint( + const std::vector& items, + Counter part_pos_1, + Counter part_pos_2, + LengthDbl& best_value) const; + + /** Value of a constraint in a state (minus its spacing). */ + LengthDbl value( + const std::vector& items, + const Constraint& constraint) const; + + /** + * Compute the constraints of the pairs of parts whose boxes, expanded by + * the maximum moves of their items, intersect; return the smallest + * separation of the state. + */ + LengthDbl compute_constraints( + const std::vector& items, + const std::vector& movements, + std::vector& constraints) const; + + /** Instance. */ + const Instance& instance_; + + /** Bin type. */ + BinTypeId bin_type_id_; + + /** Parts of the items and of the obstacles. */ + std::vector parts_; + + /** Bounding boxes of the items, at full scale, relatively to their reference points. */ + std::vector items_aabbs_; + + /** Item-item minimum spacing. */ + LengthDbl item_spacing_ = 0.0; + + /** Item-bin minimum spacing. */ + LengthDbl bin_spacing_ = 0.0; + + /** Largest minimum spacing. */ + LengthDbl maximum_spacing_ = 0.0; + + /** True iff the model supports the items. */ + bool supported_ = true; + +}; + +} +} diff --git a/src/irregular/linear_programming/separator.cpp b/src/irregular/linear_programming/separator.cpp new file mode 100644 index 000000000..18e6bdd59 --- /dev/null +++ b/src/irregular/linear_programming/separator.cpp @@ -0,0 +1,447 @@ +#include "irregular/linear_programming/separator.hpp" + +#include "irregular/utils.hpp" +#include "irregular/solution_builder.hpp" + +#include +#include +#include + +using namespace packingsolver; +using namespace packingsolver::irregular; + +namespace +{ + +/** Scale below which an item is considered shrunk. */ +const double full_scale = 1.0 - 1e-6; + +} + +LinearProgrammingSeparator::LinearProgrammingSeparator( + const Instance& instance, + const LinearProgrammingSeparatorParameters& parameters, + std::mt19937_64& generator): + instance_(instance), + parameters_(parameters), + generator_(generator()), + decomposition_(std::make_shared( + compute_instance_basic_shape_decomposition(instance))) +{ + for (ItemTypeId item_type_id = 0; + item_type_id < instance.number_of_item_types(); + ++item_type_id) { + const ItemType& item_type = instance.item_type(item_type_id); + for (ItemPos copy = 0; copy < item_type.copies - item_type.copies_fixed; ++copy) { + items_item_type_id_.push_back(item_type_id); + items_area_.push_back(item_type.area_scaled); + } + } + items_state_.resize(items_item_type_id_.size()); + items_weight_.resize(items_item_type_id_.size(), 1.0); +} + +void LinearProgrammingSeparator::random_orientation( + ItemTypeId item_type_id, + Angle& angle, + bool& mirror) +{ + const ItemType& item_type = instance_.item_type(item_type_id); + std::uniform_int_distribution distribution(0, item_type.allowed_rotations.size() - 1); + const AllowedRotation& rotation = item_type.allowed_rotations[distribution(generator_)]; + angle = rotation.start_angle; + mirror = rotation.mirror; +} + +void LinearProgrammingSeparator::random_placement( + ItemPos item_pos, + ItemState& item_state) +{ + std::uniform_int_distribution bin_distribution(0, instance_.number_of_bins() - 1); + item_state.bin_pos = bin_distribution(generator_); + random_orientation(items_item_type_id_[item_pos], item_state.angle, item_state.mirror); + const BinType& bin_type = instance_.bin_type(instance_.bin_type_id(item_state.bin_pos)); + std::uniform_real_distribution distribution_x( + bin_type.aabb_scaled.x_min, + bin_type.aabb_scaled.x_max); + std::uniform_real_distribution distribution_y( + bin_type.aabb_scaled.y_min, + bin_type.aabb_scaled.y_max); + item_state.position = {distribution_x(generator_), distribution_y(generator_)}; + item_state.lambda = 0.0; +} + +void LinearProgrammingSeparator::set_solution( + const Solution& solution, + const optimizationtools::Timer& timer) +{ + (void)timer; + const LengthDbl scale_value = instance_.parameters().scale_value; + Layout layout(items_item_type_id_.size()); + + // Items of each item type. + std::vector> item_types_items(instance_.number_of_item_types()); + for (ItemPos item_pos = (ItemPos)items_item_type_id_.size() - 1; item_pos >= 0; --item_pos) + item_types_items[items_item_type_id_[item_pos]].push_back(item_pos); + + // Bins of each bin type, in order. + std::vector> bin_types_bins(instance_.number_of_bin_types()); + for (BinPos bin_pos = instance_.number_of_bins() - 1; bin_pos >= 0; --bin_pos) + bin_types_bins[instance_.bin_type_id(bin_pos)].push_back(bin_pos); + + for (BinPos solution_bin_pos = 0; + solution_bin_pos < solution.number_of_different_bins(); + ++solution_bin_pos) { + const SolutionBin& solution_bin = solution.bin(solution_bin_pos); + for (BinPos copy = 0; copy < solution_bin.copies; ++copy) { + std::vector& bins = bin_types_bins[solution_bin.bin_type_id]; + if (bins.empty()) + break; + BinPos bin_pos = bins.back(); + bins.pop_back(); + for (const SolutionItem& solution_item: solution_bin.items) { + if (solution_item.is_fixed) + continue; + std::vector& items = item_types_items[solution_item.item_type_id]; + if (items.empty()) + continue; + ItemPos item_pos = items.back(); + items.pop_back(); + ItemState& item_state = layout[item_pos]; + item_state.bin_pos = bin_pos; + item_state.angle = solution_item.angle; + item_state.mirror = solution_item.mirror; + item_state.position = { + scale_value * solution_item.bl_corner.x, + scale_value * solution_item.bl_corner.y}; + item_state.lambda = 1.0; + } + } + } + + // Items sticking out of their bin: remove a slice of the bin at a random + // position, and shift the items after it. + for (BinPos bin_pos = 0; bin_pos < instance_.number_of_bins(); ++bin_pos) { + const BinType& bin_type = instance_.bin_type(instance_.bin_type_id(bin_pos)); + AxisAlignedBoundingBox items_aabb; + bool empty = true; + std::vector aabbs(layout.size()); + for (ItemPos item_pos = 0; item_pos < (ItemPos)layout.size(); ++item_pos) { + const ItemState& item_state = layout[item_pos]; + if (item_state.bin_pos != bin_pos) + continue; + AxisAlignedBoundingBox aabb = instance_.item_type(items_item_type_id_[item_pos]).compute_min_max( + item_state.angle, + item_state.mirror, + 1); + aabb.shift(item_state.position); + aabbs[item_pos] = aabb; + items_aabb = merge(items_aabb, aabb); + empty = false; + } + if (empty) + continue; + LengthDbl overflow_x = items_aabb.x_max - bin_type.aabb_scaled.x_max; + if (overflow_x > 0) { + std::uniform_real_distribution distribution( + bin_type.aabb_scaled.x_min, + bin_type.aabb_scaled.x_max); + LengthDbl split = distribution(generator_); + for (ItemPos item_pos = 0; item_pos < (ItemPos)layout.size(); ++item_pos) { + if (layout[item_pos].bin_pos != bin_pos) + continue; + if ((aabbs[item_pos].x_min + aabbs[item_pos].x_max) / 2 > split) + layout[item_pos].position.x -= overflow_x; + } + } + LengthDbl overflow_y = items_aabb.y_max - bin_type.aabb_scaled.y_max; + if (overflow_y > 0) { + std::uniform_real_distribution distribution( + bin_type.aabb_scaled.y_min, + bin_type.aabb_scaled.y_max); + LengthDbl split = distribution(generator_); + for (ItemPos item_pos = 0; item_pos < (ItemPos)layout.size(); ++item_pos) { + if (layout[item_pos].bin_pos != bin_pos) + continue; + if ((aabbs[item_pos].y_min + aabbs[item_pos].y_max) / 2 > split) + layout[item_pos].position.y -= overflow_y; + } + } + } + + // Missing items: random placement. + if (instance_.number_of_bins() > 0) + for (ItemPos item_pos = 0; item_pos < (ItemPos)layout.size(); ++item_pos) + if (layout[item_pos].bin_pos == -1) + random_placement(item_pos, layout[item_pos]); + + items_state_ = layout; +} + +std::vector LinearProgrammingSeparator::bin_items( + BinPos bin_pos, + std::vector& item_positions) const +{ + const LengthDbl scale_value = instance_.parameters().scale_value; + std::vector items; + item_positions.clear(); + for (ItemPos item_pos = 0; item_pos < (ItemPos)items_state_.size(); ++item_pos) { + const ItemState& item_state = items_state_[item_pos]; + if (item_state.bin_pos != bin_pos) + continue; + SeparationModelItem item; + item.item_type_id = items_item_type_id_[item_pos]; + item.angle = item_state.angle; + item.mirror = item_state.mirror; + item.position = item_state.position; + item.lambda = item_state.lambda; + item.weight = items_weight_[item_pos] * items_area_[item_pos]; + items.push_back(item); + item_positions.push_back(item_pos); + } + const BinType& bin_type = instance_.bin_type(instance_.bin_type_id(bin_pos)); + for (const auto& fixed_item: bin_type.fixed_items) { + SeparationModelItem item; + item.item_type_id = fixed_item.item_type_id; + item.angle = fixed_item.angle; + item.mirror = fixed_item.mirror; + item.is_fixed = true; + item.position = {scale_value * fixed_item.bl_corner.x, scale_value * fixed_item.bl_corner.y}; + items.push_back(item); + item_positions.push_back(-1); + } + return items; +} + +LengthDbl LinearProgrammingSeparator::separation() const +{ + LengthDbl separation = std::numeric_limits::infinity(); + std::vector item_positions; + for (BinPos bin_pos = 0; bin_pos < instance_.number_of_bins(); ++bin_pos) { + std::vector items = bin_items(bin_pos, item_positions); + if (items.empty()) + continue; + BinSeparationModel model(instance_, *decomposition_, instance_.bin_type_id(bin_pos), items); + if (!model.supported()) { + throw std::invalid_argument( + FUNC_SIGNATURE + ": " + "the shapes must be made of line segments."); + } + separation = (std::min)(separation, model.separation(items)); + } + return separation; +} + +bool LinearProgrammingSeparator::step( + const optimizationtools::Timer& timer, + double movement_ratio) +{ + std::vector item_positions; + for (BinPos bin_pos = 0; bin_pos < instance_.number_of_bins(); ++bin_pos) { + std::vector items = bin_items(bin_pos, item_positions); + bool movable = false; + for (const SeparationModelItem& item: items) + if (!item.is_fixed) + movable = true; + if (!movable) + continue; + BinSeparationModel model(instance_, *decomposition_, instance_.bin_type_id(bin_pos), items); + if (!model.supported()) { + throw std::invalid_argument( + FUNC_SIGNATURE + ": " + "the shapes must be made of line segments."); + } + BinSeparationModel::StepParameters step_parameters; + step_parameters.movement_ratio = movement_ratio; + step_parameters.shrink = true; + step_parameters.target_separation = 0.0; + // Eta first: its weight is larger than the largest possible gain on + // the scales. + double weights_sum = 0.0; + for (const SeparationModelItem& item: items) + weights_sum += item.weight; + step_parameters.eta_weight = 1e6 * (1.0 + weights_sum); + if (!model.step(items, step_parameters, timer)) + return false; + for (Counter pos = 0; pos < (Counter)items.size(); ++pos) { + ItemPos item_pos = item_positions[pos]; + if (item_pos == -1) + continue; + items_state_[item_pos].position = items[pos].position; + items_state_[item_pos].lambda = items[pos].lambda; + } + } + + // Guided local search: the weights of the shrunk items increase. + for (ItemPos item_pos = 0; item_pos < (ItemPos)items_state_.size(); ++item_pos) + if (items_state_[item_pos].lambda < full_scale) + items_weight_[item_pos] += 1.0; + return true; +} + +double LinearProgrammingSeparator::total_loss() const +{ + double loss = 0.0; + double total_area = 0.0; + for (ItemPos item_pos = 0; item_pos < (ItemPos)items_state_.size(); ++item_pos) { + const ItemState& item_state = items_state_[item_pos]; + total_area += items_area_[item_pos]; + double lambda = (item_state.bin_pos == -1)? 0.0: item_state.lambda; + loss += items_area_[item_pos] * (1.0 - lambda); + } + LengthDbl separation = this->separation(); + if (separation < -parameters_.tolerance) + loss = total_area - separation; + return loss; +} + +bool LinearProgrammingSeparator::separate( + const optimizationtools::Timer& timer, + double reference_loss, + Counter maximum_number_of_iterations_without_improvement) +{ + double loss_best = total_loss(); + Layout layout_best = items_state_; + Counter number_of_iterations_without_improvement = 0; + // Trust region: halved after each linear program without improvement, + // the next one starting again from the best layout. + double movement_ratio = parameters_.movement_ratio; + for (;;) { + // Success: all the items have their full size, without overlap. + bool full = true; + for (const ItemState& item_state: items_state_) + if (item_state.bin_pos == -1 || item_state.lambda < full_scale) + full = false; + if (full) { + Layout layout = items_state_; + for (ItemState& item_state: items_state_) + item_state.lambda = 1.0; + if (separation() >= -parameters_.tolerance) + return true; + items_state_ = layout; + } + + Counter maximum_number_of_iterations = (loss_best < reference_loss)? + maximum_number_of_iterations_without_improvement: + (std::min)( + maximum_number_of_iterations_without_improvement, + parameters_.maximum_number_of_iterations_without_improvement_above_reference); + if (number_of_iterations_without_improvement >= maximum_number_of_iterations + || timer.needs_to_end()) { + break; + } + if (!step(timer, movement_ratio)) + break; + double loss = total_loss(); + if (loss < loss_best - 1e-9 * (1.0 + std::abs(loss_best))) { + loss_best = loss; + layout_best = items_state_; + number_of_iterations_without_improvement = 0; + } else { + number_of_iterations_without_improvement++; + items_state_ = layout_best; + movement_ratio = (std::max)( + parameters_.minimum_movement_ratio, + movement_ratio / 2); + } + } + items_state_ = layout_best; + return false; +} + +bool LinearProgrammingSeparator::separate( + const optimizationtools::Timer& timer, + double reference_loss) +{ + return separate( + timer, + reference_loss, + parameters_.maximum_number_of_iterations_without_improvement); +} + +bool LinearProgrammingSeparator::separate_initial(const optimizationtools::Timer& timer) +{ + return separate( + timer, + std::numeric_limits::infinity(), + parameters_.initial_maximum_number_of_iterations_without_improvement); +} + +void LinearProgrammingSeparator::disrupt() +{ + // Most shrunk item. + ItemPos item_pos_shrunk = -1; + for (ItemPos item_pos = 0; item_pos < (ItemPos)items_state_.size(); ++item_pos) { + if (items_state_[item_pos].lambda >= full_scale) + continue; + if (item_pos_shrunk == -1 + || items_state_[item_pos].lambda < items_state_[item_pos_shrunk].lambda) { + item_pos_shrunk = item_pos; + } + } + if (item_pos_shrunk == -1 || instance_.number_of_bins() == 0) + return; + + random_placement(item_pos_shrunk, items_state_[item_pos_shrunk]); +} + +double LinearProgrammingSeparator::distance( + const Layout& layout_1, + const Layout& layout_2) const +{ + if (layout_1.empty()) + return 0.0; + double distance = 0.0; + for (ItemPos item_pos = 0; item_pos < (ItemPos)layout_1.size(); ++item_pos) { + const ItemState& item_state_1 = layout_1[item_pos]; + const ItemState& item_state_2 = layout_2[item_pos]; + if (item_state_1.bin_pos != item_state_2.bin_pos + || item_state_1.angle != item_state_2.angle + || item_state_1.mirror != item_state_2.mirror) { + distance += 1.0; + continue; + } + LengthDbl delta_x = item_state_1.position.x - item_state_2.position.x; + LengthDbl delta_y = item_state_1.position.y - item_state_2.position.y; + LengthDbl size = std::sqrt(items_area_[item_pos]); + distance += (std::min)(1.0, std::sqrt(delta_x * delta_x + delta_y * delta_y) / size); + } + return distance / layout_1.size(); +} + +Solution LinearProgrammingSeparator::solution() const +{ + const LengthDbl scale_value = instance_.parameters().scale_value; + SolutionBuilder solution_builder(instance_); + for (BinPos bin_pos = 0; bin_pos < instance_.number_of_bins(); ++bin_pos) { + const BinType& bin_type = instance_.bin_type(instance_.bin_type_id(bin_pos)); + bool empty = bin_type.fixed_items.empty(); + for (const ItemState& item_state: items_state_) + if (item_state.bin_pos == bin_pos) + empty = false; + if (empty) + continue; + BinPos solution_bin_pos = solution_builder.add_bin(instance_.bin_type_id(bin_pos), 1); + for (const auto& fixed_item: bin_type.fixed_items) { + solution_builder.add_item( + solution_bin_pos, + fixed_item.item_type_id, + fixed_item.bl_corner, + fixed_item.angle, + fixed_item.mirror, + true); + } + for (ItemPos item_pos = 0; item_pos < (ItemPos)items_state_.size(); ++item_pos) { + const ItemState& item_state = items_state_[item_pos]; + if (item_state.bin_pos != bin_pos) + continue; + solution_builder.add_item( + solution_bin_pos, + items_item_type_id_[item_pos], + {item_state.position.x / scale_value, item_state.position.y / scale_value}, + item_state.angle, + item_state.mirror); + } + } + return solution_builder.build(); +} diff --git a/src/irregular/linear_programming/separator.hpp b/src/irregular/linear_programming/separator.hpp new file mode 100644 index 000000000..3c1b11602 --- /dev/null +++ b/src/irregular/linear_programming/separator.hpp @@ -0,0 +1,222 @@ +/** + * Separator of the local search with the linear programming engine + * + * The items may be shrunk instead of overlapping: an item with scale 'lambda' + * is its shape scaled by 'lambda' around its reference point. A separation + * solves linear programs (see 'BinSeparationModel') which move the items + * slightly and maximize their weighted scales; the weights of the items which + * stay shrunk increase, as in guided local search. It succeeds when all the + * items have their full size, without overlap. + */ + +#pragma once + +#include "irregular/linear_programming/separation_model.hpp" + +#include "packingsolver/irregular/solution.hpp" + +#include +#include + +namespace packingsolver +{ +namespace irregular +{ + +struct InstanceBasicShapeDecomposition; + +struct LinearProgrammingSeparatorParameters +{ + /** + * Maximum move of an item, in each direction, in each linear program, + * relatively to the largest side of its bounding box. + */ + double movement_ratio = 0.05; + + /** + * Smallest movement ratio: after a linear program which doesn't improve + * the loss, the movement ratio is halved, down to this value (trust + * region). + */ + double minimum_movement_ratio = 1e-4; + + /** + * Maximum number of linear programs without improvement of the loss of + * a separation. + */ + Counter maximum_number_of_iterations_without_improvement = 4; + + /** + * Same as 'maximum_number_of_iterations_without_improvement', while the + * loss isn't smaller than the reference loss (see 'separate'). + */ + Counter maximum_number_of_iterations_without_improvement_above_reference = 2; + + /** + * Same as 'maximum_number_of_iterations_without_improvement', for the + * separation of the initial layout. + */ + Counter initial_maximum_number_of_iterations_without_improvement = 24; + + /** + * Penetration below which two shapes are considered touching, in scaled + * coordinates. + */ + LengthDbl tolerance = 1e-7; +}; + +class LinearProgrammingSeparator +{ + +public: + + /** State of an item. */ + struct ItemState + { + /** Bin, or -1 if the item isn't packed. */ + BinPos bin_pos = -1; + + /** Angle. */ + Angle angle = 0.0; + + /** Mirror. */ + bool mirror = false; + + /** Position of the reference point, in scaled coordinates. */ + Point position = {0.0, 0.0}; + + /** Scale. */ + double lambda = 1.0; + }; + + /** Layout: the states of the items. */ + using Layout = std::vector; + + /** Constructor. */ + LinearProgrammingSeparator( + const Instance& instance, + const LinearProgrammingSeparatorParameters& parameters, + std::mt19937_64& generator); + + /** + * Load a solution of the instance. + * + * The items missing from the solution are inserted at random positions, + * with a null scale. + */ + void set_solution( + const Solution& solution, + const optimizationtools::Timer& timer); + + /** + * Try to make all the items reach their full size without overlap. + * + * Return true iff successful. In any case, the current layout is the one + * with the smallest loss found. + * + * While the smallest loss found isn't smaller than 'reference_loss', the + * separation stops after + * 'maximum_number_of_iterations_without_improvement_above_reference' + * linear programs without improvement instead of + * 'maximum_number_of_iterations_without_improvement'. + */ + bool separate( + const optimizationtools::Timer& timer, + double reference_loss = std::numeric_limits::infinity()); + + /** Same as 'separate', with more effort, for the initial layout. */ + bool separate_initial(const optimizationtools::Timer& timer); + + /** Get the current layout. */ + const Layout& layout() const { return items_state_; } + + /** Set the current layout; the weights are kept. */ + void set_layout(const Layout& layout) { items_state_ = layout; } + + /** + * Disrupt the current layout: take the most shrunk item out, and insert + * it again in a random bin, at a random position, with a random allowed + * orientation and a null scale. + */ + void disrupt(); + + /** Distance between two layouts, in [0, 1]. */ + double distance( + const Layout& layout_1, + const Layout& layout_2) const; + + /** + * Get the loss of the current layout: the area missing from the shrunk + * items, plus the largest penetration for an infeasible layout. + */ + double total_loss() const; + + /** Get the solution of the current layout. */ + Solution solution() const; + +private: + + /** Run the linear programs of a separation. */ + bool separate( + const optimizationtools::Timer& timer, + double reference_loss, + Counter maximum_number_of_iterations_without_improvement); + + /** Run a linear program on each bin; return false if one fails. */ + bool step( + const optimizationtools::Timer& timer, + double movement_ratio); + + /** + * Compute the smallest separation of the current layout, over all the + * bins. + */ + LengthDbl separation() const; + + /** Items of the separation model of a bin, from the current layout. */ + std::vector bin_items( + BinPos bin_pos, + std::vector& item_positions) const; + + /** + * Random placement of an item: random bin, allowed orientation and + * position, null scale. + */ + void random_placement( + ItemPos item_pos, + ItemState& item_state); + + /** Random allowed orientation of an item type. */ + void random_orientation( + ItemTypeId item_type_id, + Angle& angle, + bool& mirror); + + /** Instance. */ + const Instance& instance_; + + /** Parameters. */ + LinearProgrammingSeparatorParameters parameters_; + + /** Random number generator. */ + std::mt19937_64 generator_; + + /** Convex decomposition of the instance. */ + std::shared_ptr decomposition_; + + /** Item type of each item. */ + std::vector items_item_type_id_; + + /** Area of each item (scaled). */ + std::vector items_area_; + + /** Current layout. */ + Layout items_state_; + + /** Weights of the scales of the items. */ + std::vector items_weight_; + +}; + +} +} diff --git a/src/irregular/local_search.cpp b/src/irregular/local_search.cpp index 082c5856e..82255483a 100644 --- a/src/irregular/local_search.cpp +++ b/src/irregular/local_search.cpp @@ -1,6 +1,6 @@ #include "irregular/local_search.hpp" #include "irregular/sequential_feasibility.hpp" -#include "irregular/linear_programming.hpp" +#include "irregular/linear_programming/separator.hpp" #include "irregular/solution_builder.hpp" #include "packingsolver/irregular/algorithm_formatter.hpp" @@ -22,362 +22,31 @@ using namespace packingsolver::irregular; namespace { -struct LocalSearchBinData -{ - /** Penalty per item position in this bin. */ - std::vector item_penalties; - - /** Lambda (scale factor) per item position in this bin. */ - std::vector lambda; - - /** Remaining area in this bin (heuristic for bin selection). */ - AreaDbl remaining_area = 0; -}; - -/** - * Assign a single item to the solution. Chooses a random orientation and - * places the item inside the largest free region of the selected bin (boolean - * difference of the bin AABB minus existing item shapes, defects, and - * borders). The bin is the valid one (item AABB fits) with the most remaining - * area; falls back to the bin with the most remaining area if none fits. - * Returns the bin position the item was placed in, or -1 if the selected bin - * has no free space left (the item is then not added). - */ -BinPos assign_item_to_bin( - const Instance& instance, - std::mt19937_64& rng, - ItemTypeId item_type_id, - Solution& solution, - const std::vector& bin_data) -{ - const ItemType& item_type = instance.item_type(item_type_id); - - // Choose a random allowed rotation entry, then a random angle within it. - std::uniform_int_distribution range_dist( - 0, (Counter)item_type.allowed_rotations.size() - 1); - const AllowedRotation& rotation_range = item_type.allowed_rotations[range_dist(rng)]; - std::uniform_real_distribution angle_dist( - rotation_range.start_angle, rotation_range.end_angle); - const Angle angle = angle_dist(rng); - const bool mirror = rotation_range.mirror; - - const AxisAlignedBoundingBox item_aabb = item_type.compute_min_max(angle, mirror); - - // Select the valid bin (item fits at full scale) with the most remaining area. - // Fall back to the bin with the most remaining area if no bin fits. - BinPos best_bin_pos = -1; - AreaDbl best_remaining = -std::numeric_limits::infinity(); - for (BinPos bin_pos = 0; - bin_pos < (BinPos)solution.number_of_different_bins(); - ++bin_pos) { - const BinTypeId bin_type_id = solution.bin(bin_pos).bin_type_id; - const BinType& bin_type = instance.bin_type(bin_type_id); - if (bin_type.aabb_orig.x_max - bin_type.aabb_orig.x_min < item_aabb.x_max - item_aabb.x_min - || bin_type.aabb_orig.y_max - bin_type.aabb_orig.y_min < item_aabb.y_max - item_aabb.y_min) - continue; - if (bin_data[bin_pos].remaining_area > best_remaining) { - best_remaining = bin_data[bin_pos].remaining_area; - best_bin_pos = bin_pos; - } - } - if (best_bin_pos == -1) { - best_bin_pos = 0; - for (BinPos bin_pos = 1; - bin_pos < (BinPos)solution.number_of_different_bins(); - ++bin_pos) { - if (bin_data[bin_pos].remaining_area > bin_data[best_bin_pos].remaining_area) - best_bin_pos = bin_pos; - } - } - - // Compute the free space in the bin as the boolean difference between the - // bin AABB and the shapes of existing items, defects, and borders. - const BinTypeId best_bin_type_id = solution.bin(best_bin_pos).bin_type_id; - const BinType& best_bin_type = instance.bin_type(best_bin_type_id); - const AxisAlignedBoundingBox& bin_aabb = best_bin_type.aabb_orig; - - shape::ShapeWithHoles bin_shape{instance.parameters().scale_value * shape::build_rectangle(bin_aabb), {}}; - - std::vector occupied_shapes; - const SolutionBin& best_bin = solution.bin(best_bin_pos); - for (ItemPos item_pos = 0; - item_pos < (ItemPos)best_bin.items.size(); - ++item_pos) { - const ItemType& placed_item_type = instance.item_type(best_bin.items[item_pos].item_type_id); - for (ItemShapePos shape_pos = 0; - shape_pos < (ItemShapePos)placed_item_type.shapes.size(); - ++shape_pos) { - occupied_shapes.push_back(solution.shape_scaled(best_bin_pos, item_pos, shape_pos)); - } - } - for (const Defect& defect: best_bin_type.defects) - occupied_shapes.push_back(defect.shape_scaled); - for (const Defect& border: best_bin_type.borders) - occupied_shapes.push_back(border.shape_scaled); - - const shape::MultiShapeWithHoles free_regions_multi = shape::compute_difference( - shape::MultiShapeWithHoles{{bin_shape}}, - shape::MultiShapeWithHoles{occupied_shapes}); - const std::vector& free_regions = free_regions_multi.shapes_with_holes; - //shape::Writer().add_shape_with_holes(bin_shape, "Bin") - // .add_shapes_with_holes(occupied_shapes, "Occupied") - // .add_shapes_with_holes(free_regions, "Difference") - // .write_json("difference.json"); - - // Select the free region with the largest area. - Counter best_region_pos = -1; - AreaDbl best_area = -1.0; - for (Counter region_pos = 0; - region_pos < (Counter)free_regions.size(); - ++region_pos) { - const AreaDbl area = free_regions[region_pos].compute_area(); - if (area > best_area) { - best_area = area; - best_region_pos = region_pos; - } - } - - // If the bin has no free space left, the item can't be placed in it: a - // point inside another item can't be separated from it by the - // shrinkage LP. - if (best_region_pos == -1) - return -1; - Point bl_corner = free_regions[best_region_pos].find_point_strictly_inside(); - //std::cout << "bl_corner " << bl_corner.to_string() << std::endl; - bl_corner = 1.0 / instance.parameters().scale_value * bl_corner; - //std::cout << "bl_corner " << bl_corner.to_string() << std::endl; - SolutionBuilder solution_builder(instance); - for (BinPos bp = 0; bp < solution.number_of_different_bins(); ++bp) { - const SolutionBin& bin = solution.bin(bp); - solution_builder.add_bin(bin.bin_type_id, bin.copies); - for (const SolutionItem& item: bin.items) { - solution_builder.add_item( - bp, - item.item_type_id, - item.bl_corner, - item.angle, - item.mirror, - item.is_fixed); - } - } - solution_builder.add_item(best_bin_pos, item_type_id, bl_corner, angle, mirror); - solution = solution_builder.build(); - - return best_bin_pos; -} - -/** - * Assign an item to a bin, then run minimize_shrinkage on that bin until it - * is feasible (all items at full scale). Updates solution and bin_data in - * place. Returns false if the item fits in no bin, if feasibility wasn't - * reached within - * 'LocalSearchParameters::maximum_number_of_iterations_without_improvement' - * iterations without improvement, or if the timer or end-flag fired before - * feasibility was reached. - */ -bool pack_item( - const Instance& instance, - std::mt19937_64& rng, - ItemTypeId item_type_id, - Solution& solution, - std::vector& bin_data, - AlgorithmFormatter& algorithm_formatter, - const LocalSearchParameters& parameters) -{ - if (algorithm_formatter.end_boolean() || parameters.timer.needs_to_end()) - return false; - - // 'optimize_item_types_fit' only checks the original instance: the bins - // of the sub-instances built by 'sequential_feasibility' are narrower. - if (!instance.fits_some_bin(item_type_id)) - return false; - - const ItemType& item_type = instance.item_type(item_type_id); - - const BinPos bin_pos = assign_item_to_bin( - instance, rng, item_type_id, solution, bin_data); - if (bin_pos == -1) - return false; - - bin_data[bin_pos].remaining_area -= item_type.area_scaled; - bin_data[bin_pos].item_penalties.push_back(1.0); - bin_data[bin_pos].lambda.push_back(0.0); - - Solution bin_solution(instance); - bin_solution.append_bin(solution, bin_pos, 1); - - bool bin_feasible = false; - // Sum of the scale factors of the items of the bin: it measures how far - // the bin is from being feasible. - double best_lambda_sum = -1; - Counter number_of_iterations_without_improvement = 0; - while (!bin_feasible) { - if (algorithm_formatter.end_boolean() || parameters.timer.needs_to_end()) - return false; - if (parameters.maximum_number_of_iterations_without_improvement != -1 - && number_of_iterations_without_improvement - >= parameters.maximum_number_of_iterations_without_improvement) { - return false; - } - - LinearProgrammingMinimizeShrinkageParameters lp_params; - lp_params.timer = parameters.timer; - - const LinearProgrammingMinimizeShrinkageOutput lp_output = - linear_programming_minimize_shrinkage( - bin_solution, - bin_data[bin_pos].lambda, - bin_data[bin_pos].item_penalties, - lp_params); - - bin_feasible = lp_output.feasible; - bin_data[bin_pos].lambda = lp_output.final_lambda; - - double lambda_sum = 0; - for (double lambda: lp_output.final_lambda) - lambda_sum += lambda; - if (shape::strictly_greater(lambda_sum, best_lambda_sum)) { - best_lambda_sum = lambda_sum; - number_of_iterations_without_improvement = 0; - } else { - number_of_iterations_without_improvement++; - } - - for (ItemPos item_pos = 0; - item_pos < (ItemPos)lp_output.items_shrunken.size(); - ++item_pos) { - if (lp_output.items_shrunken[item_pos]) - bin_data[bin_pos].item_penalties[item_pos] += 1.0; - } - - bin_solution = lp_output.solution; - } - - // Rebuild solution with the updated bin. - Solution new_solution(instance); - for (BinPos bp = 0; bp < solution.number_of_bins(); ++bp) { - if (bp == bin_pos) { - new_solution.append_bin(bin_solution, 0, 1); - } else { - new_solution.append_bin(solution, bp, 1); - } - } - solution = std::move(new_solution); - return true; -} - -/** - * Local search with the linear programming engine, for objective Feasibility. - */ -void local_search_linear_programming( - const Instance& instance, - std::mt19937_64& generator, - const LocalSearchParameters& parameters, - AlgorithmFormatter& algorithm_formatter) -{ - - SolutionBuilder solution_builder(instance); - for (BinPos bin_pos = 0; bin_pos < instance.number_of_bins(); ++bin_pos) - solution_builder.add_bin(instance.bin_type_id(bin_pos), 1); - - // Pre-place fixed items and initialize their bin_data entries. - // Per-bin state. - std::vector bin_data(instance.number_of_bins()); - for (BinPos bin_pos = 0; bin_pos < instance.number_of_bins(); ++bin_pos) { - const BinType& bin_type = instance.bin_type(instance.bin_type_id(bin_pos)); - bin_data[bin_pos].remaining_area = bin_type.area_scaled; - for (const FixedItem& fixed_item: bin_type.fixed_items) { - const ItemType& item_type = instance.item_type(fixed_item.item_type_id); - solution_builder.add_item( - bin_pos, - fixed_item.item_type_id, - fixed_item.bl_corner, - fixed_item.angle, - fixed_item.mirror, - true); - bin_data[bin_pos].remaining_area -= item_type.area_scaled; - bin_data[bin_pos].item_penalties.push_back( - std::numeric_limits::infinity()); - bin_data[bin_pos].lambda.push_back(1.0); - } - } - Solution solution = solution_builder.build(); - - // Build a flat list of all remaining item copies sorted ascending by area - // so that pop_back processes the largest items first. - // Exclude copies already fixed in the bin types. - std::vector unpacked_items; - unpacked_items.reserve(instance.number_of_items()); - for (ItemTypeId item_type_id = 0; - item_type_id < instance.number_of_item_types(); - ++item_type_id) { - const ItemType& item_type = instance.item_type(item_type_id); - for (ItemPos copy = 0; copy < item_type.copies - item_type.copies_fixed; ++copy) - unpacked_items.push_back(item_type_id); - } - std::sort(unpacked_items.begin(), unpacked_items.end(), - [&](ItemTypeId a, ItemTypeId b) { - return instance.item_type(a).area_orig < instance.item_type(b).area_orig; - }); - - // Pack all items into the available bins. - while (!unpacked_items.empty()) { - if (algorithm_formatter.end_boolean() || parameters.timer.needs_to_end()) - break; - const ItemTypeId item_type_id = unpacked_items.back(); - unpacked_items.pop_back(); - if (!pack_item( - instance, - generator, - item_type_id, - solution, - bin_data, - algorithm_formatter, - parameters)) - break; - } - - algorithm_formatter.update_solution(solution, ""); -} - /** - * Local search with the direct trigonometry engine, for objective - * Feasibility. + * Population-based iterated local search, for objective Feasibility, on top of + * a separator (direct trigonometry or linear programming engine) already + * loaded with the initial layout. * - * Population-based iterated local search, generalizing the exploration phase - * of Sparrow at a fixed bin size: the initial layout is separated; then, while - * the separations fail, their layouts are added to a population, and the next - * separation starts from a disruption of a layout drawn from the population. - * It is given up early if its loss doesn't get below the loss of this layout. + * The initial layout is separated; then, while the separations fail, their + * layouts are added to a population, and the next separation starts from a + * disruption of a layout drawn from the population. It is given up early if + * its loss doesn't get below the loss of this layout. */ -void local_search_direct_trigonometry( - const Instance& instance, +template +void run_iterated_local_search( + SeparatorType& separator, std::mt19937_64& generator, - const Solution* initial_solution, const LocalSearchParameters& parameters, AlgorithmFormatter& algorithm_formatter) { - Separator separator( - instance, - parameters.separator_parameters, - generator, - parameters.separator_item_types); - if (initial_solution != nullptr) { - separator.set_solution( - convert_initial_solution(instance, *initial_solution), - parameters.timer); - } else { - separator.set_solution(Solution(instance), parameters.timer); - } - // Layouts of the failed separations. struct FailedLayout { - std::vector layout; + typename SeparatorType::Layout layout; double loss; }; - localsearchsolver::Population::Parameters population_parameters; + typename localsearchsolver::Population::Parameters population_parameters; population_parameters.minimum_size = parameters.population_minimum_size; population_parameters.maximum_size = parameters.population_maximum_size; population_parameters.number_of_elite_solutions = parameters.population_number_of_elite_solutions; @@ -417,17 +86,7 @@ void local_search_direct_trigonometry( // Separation of the initial layout, with more effort. if (algorithm_formatter.end_boolean() || parameters.timer.needs_to_end()) return; - separator.set_stopping_criteria( - (parameters.initial_separation_maximum_number_of_iterations_without_improvement != -1)? - parameters.initial_separation_maximum_number_of_iterations_without_improvement: - parameters.separator_parameters.maximum_number_of_iterations_without_improvement, - (parameters.initial_separation_maximum_number_of_strikes != -1)? - parameters.initial_separation_maximum_number_of_strikes: - parameters.separator_parameters.maximum_number_of_strikes); - bool separated = separator.separate(parameters.timer); - separator.set_stopping_criteria( - parameters.separator_parameters.maximum_number_of_iterations_without_improvement, - parameters.separator_parameters.maximum_number_of_strikes); + bool separated = separator.separate_initial(parameters.timer); if (process_separation(separated, 0)) return; @@ -452,6 +111,54 @@ void local_search_direct_trigonometry( } } +/** Local search with the direct trigonometry engine, for objective Feasibility. */ +void local_search_direct_trigonometry( + const Instance& instance, + std::mt19937_64& generator, + const Solution* initial_solution, + const LocalSearchParameters& parameters, + AlgorithmFormatter& algorithm_formatter) +{ + Separator separator( + instance, + parameters.separator_parameters, + generator, + parameters.separator_item_types); + separator.set_initial_stopping_criteria( + parameters.initial_separation_maximum_number_of_iterations_without_improvement, + parameters.initial_separation_maximum_number_of_strikes); + if (initial_solution != nullptr) { + separator.set_solution( + convert_initial_solution(instance, *initial_solution), + parameters.timer); + } else { + separator.set_solution(Solution(instance), parameters.timer); + } + run_iterated_local_search(separator, generator, parameters, algorithm_formatter); +} + +/** Local search with the linear programming engine, for objective Feasibility. */ +void local_search_linear_programming( + const Instance& instance, + std::mt19937_64& generator, + const Solution* initial_solution, + const LocalSearchParameters& parameters, + AlgorithmFormatter& algorithm_formatter) +{ + LinearProgrammingSeparator separator( + instance, + parameters.linear_programming_separator_parameters, + generator); + if (initial_solution != nullptr) { + separator.set_solution( + convert_initial_solution(instance, *initial_solution), + parameters.timer); + } else { + separator.set_solution(Solution(instance), parameters.timer); + } + run_iterated_local_search(separator, generator, parameters, algorithm_formatter); +} + } // namespace Solution packingsolver::irregular::convert_initial_solution( @@ -559,6 +266,8 @@ LocalSearchOutput packingsolver::irregular::local_search( inner_parameters.engine = parameters.engine; inner_parameters.shrink_ratio = parameters.shrink_ratio; inner_parameters.separator_parameters = parameters.separator_parameters; + inner_parameters.linear_programming_separator_parameters + = parameters.linear_programming_separator_parameters; inner_parameters.separator_item_types = separator_item_types; inner_parameters.initial_separation_maximum_number_of_iterations_without_improvement = parameters.initial_separation_maximum_number_of_iterations_without_improvement; @@ -572,8 +281,6 @@ LocalSearchOutput packingsolver::irregular::local_search( = parameters.population_number_of_elite_solutions; inner_parameters.population_number_of_closest_neighbors = parameters.population_number_of_closest_neighbors; - inner_parameters.maximum_number_of_iterations_without_improvement - = parameters.maximum_number_of_iterations_without_improvement; // The first sub-problem has no previous solution: warm start it // from the initial solution. return local_search( @@ -609,7 +316,7 @@ LocalSearchOutput packingsolver::irregular::local_search( algorithm_formatter.print_header(); if (parameters.engine == LocalSearchEngine::LinearProgramming) { - local_search_linear_programming(instance, generator, parameters, algorithm_formatter); + local_search_linear_programming(instance, generator, initial_solution, parameters, algorithm_formatter); } else { local_search_direct_trigonometry(instance, generator, initial_solution, parameters, algorithm_formatter); } diff --git a/src/irregular/local_search.hpp b/src/irregular/local_search.hpp index a3bacb040..9b3f7d549 100644 --- a/src/irregular/local_search.hpp +++ b/src/irregular/local_search.hpp @@ -7,7 +7,8 @@ #pragma once -#include "irregular/local_search_direct_trigonometry/separator.hpp" +#include "irregular/direct_trigonometry/separator.hpp" +#include "irregular/linear_programming/separator.hpp" #include "packingsolver/irregular/optimize.hpp" @@ -130,13 +131,8 @@ struct LocalSearchParameters: packingsolver::Parameters(), "") ("not-anytime-sequential-single-knapsack-subproblem-tree-search-queue-size,", po::value(), "") ("not-anytime-sequential-value-correction-number-of-iterations,", po::value(), "") - ("not-anytime-local-search-maximum-number-of-iterations-without-improvement,", po::value(), "") ("not-anytime-local-search-maximum-number-of-failed-separations,", po::value(), "") ("not-anytime-dichotomic-search-subproblem-tree-search-queue-size,", po::value(), "") @@ -200,8 +199,6 @@ int main(int argc, char *argv[]) parameters.not_anytime_sequential_single_knapsack_subproblem_tree_search_queue_size = vm["not-anytime-sequential-single-knapsack-subproblem-tree-search-queue-size"].as(); if (vm.count("not-anytime-sequential-value-correction-number-of-iterations")) parameters.not_anytime_sequential_value_correction_number_of_iterations = vm["not-anytime-sequential-value-correction-number-of-iterations"].as(); - if (vm.count("not-anytime-local-search-maximum-number-of-iterations-without-improvement")) - parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement = vm["not-anytime-local-search-maximum-number-of-iterations-without-improvement"].as(); if (vm.count("not-anytime-local-search-maximum-number-of-failed-separations")) parameters.not_anytime_local_search_maximum_number_of_failed_separations = vm["not-anytime-local-search-maximum-number-of-failed-separations"].as(); if (vm.count("not-anytime-dichotomic-search-subproblem-tree-search-queue-size")) diff --git a/src/irregular/optimize.cpp b/src/irregular/optimize.cpp index f7cdb1c70..d0a4c0c5d 100644 --- a/src/irregular/optimize.cpp +++ b/src/irregular/optimize.cpp @@ -318,8 +318,6 @@ void optimize_tree_search( last_bin_parameters.optimization_mode = parameters.optimization_mode; last_bin_parameters.not_anytime_maximum_approximation_ratio = parameters.not_anytime_maximum_approximation_ratio; last_bin_parameters.not_anytime_tree_search_queue_size = parameters.not_anytime_tree_search_queue_size; - last_bin_parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement - = parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement; last_bin_parameters.not_anytime_local_search_maximum_number_of_failed_separations = parameters.not_anytime_local_search_maximum_number_of_failed_separations; last_bin_parameters.tree_search_guides = {2, 3}; @@ -375,8 +373,6 @@ void optimize_local_search( if (parameters.optimization_mode == OptimizationMode::Anytime) { ls_parameters.maximum_number_of_failed_separations = -1; } else { - ls_parameters.maximum_number_of_iterations_without_improvement - = parameters.not_anytime_local_search_maximum_number_of_iterations_without_improvement; ls_parameters.maximum_number_of_failed_separations = parameters.not_anytime_local_search_maximum_number_of_failed_separations; } diff --git a/src/irregular/post_process.cpp b/src/irregular/post_process.cpp index 41eb700eb..18d615102 100644 --- a/src/irregular/post_process.cpp +++ b/src/irregular/post_process.cpp @@ -1,6 +1,6 @@ #include "packingsolver/irregular/post_process.hpp" -#include "irregular/linear_programming.hpp" +#include "irregular/linear_programming/anchor.hpp" #include "irregular/solution_builder.hpp" using namespace packingsolver; diff --git a/src/irregular/utils.hpp b/src/irregular/utils.hpp index 464414e0f..298370711 100644 --- a/src/irregular/utils.hpp +++ b/src/irregular/utils.hpp @@ -1,6 +1,5 @@ /** - * Private helpers shared between linear_programming.cpp and - * local_nonlinear_programming.cpp. + * Private helpers shared between the algorithms of the irregular problem. * * All functions are inline to allow inclusion from multiple translation units. */ @@ -13,6 +12,9 @@ #include "shape/convex_partition.hpp" #include "shape/intersection_tree.hpp" +#include +#include +#include #include namespace packingsolver @@ -368,5 +370,210 @@ inline IntersectingParts compute_potentially_intersecting_parts( return output; } +struct EdgeSeparationConstraintParameters +{ + /** Shape to which the separating line belongs. */ + ShapePos edge_shape_pos = -1; + + /** Separating element. */ + ElementPos edge_element_pos = -1; + + /** Element of the closest point. */ + ElementPos point_element_pos = -1; + + /** Closest point from the separating element. */ + Point point; + + /** Signed distance between the closest element and the separating line. */ + LengthDbl distance; + + /** + * Signed distance with the unscaled point. + * + * Used as tie-breaker when the shape scale is 0.0. + */ + LengthDbl distance_unscaled; + + + LengthDbl coef_x1; + LengthDbl coef_y1; + LengthDbl coef_x2; + LengthDbl coef_y2; + LengthDbl coef_lambda1; + LengthDbl coef_lambda2; +}; + +/** Compute the separation constraint of an edge of a shape and another shape. */ +inline EdgeSeparationConstraintParameters compute_edge_separation_constraint_parameters( + const Shape& shape_from, + const Point& shift_from, + double scale_from, + ElementPos element_from_pos, + const Shape& shape_to, + const Point& shift_to, + double scale_to) +{ + EdgeSeparationConstraintParameters output; + const ShapeElement& element_from = shape_from.elements[element_from_pos]; + output.distance = std::numeric_limits::infinity(); + for (ElementPos element_to_pos = 0; + element_to_pos < (ElementPos)shape_to.elements.size(); + ++element_to_pos) { + const ShapeElement& element_to = shape_to.elements[element_to_pos]; + const Point& point = element_to.start; + LengthDbl distance = signed_distance_point_to_line( + scale_to * point + shift_to, + scale_from * element_from.start + shift_from, + scale_from * element_from.start + shift_from + (element_from.end - element_from.start)); + LengthDbl distance_unscaled = signed_distance_point_to_line( + point + shift_to, + scale_from * element_from.start + shift_from, + scale_from * element_from.start + shift_from + (element_from.end - element_from.start)); + if (shape::strictly_lesser(distance, output.distance) + || (shape::equal(distance, output.distance) + && shape::strictly_lesser(distance_unscaled, output.distance_unscaled))) { + output.distance = distance; + output.distance_unscaled = distance_unscaled; + output.point_element_pos = element_to_pos; + output.point = point; + } + } + + // Original points: (X11, Y11) (X12, Y12) + // + // Shifted and shrunken points: (x1 + l1 * X11, y1 + l1 * Y11) (x1 + l1 * X12, y1 + l1 * Y12) + // A = l1 * (Y12 - Y11) + // B = l1 * (X11 - X12) + // C = (x1 + l1 * X12) * (y1 + l1 * Y11) - (x1 + l1 * X11) * (y1 + l1 * Y12 + // C = l1 * (x1 * (Y11 - Y12) + y1 * (X12 - X11) + l1 * (X12 Y11 - X11 Y12)) + // + // Simplify by l1: + // A = Y12 - Y11 + // B = X11 - X12 + // C = x1 * (Y11 - Y12) + y1 * (X12 - X11) + l1 * (X12 Y11 - X11 Y12) + // + // Original point: (X2, Y2) + // Shifted and shrunken point: (x2 + l2 * X2, y2 + l2 * Y2) + // Final constraint: + // A * x2 + // + B * y2 + // + (A * X2 + B * Y2) * l2 + // - A * x1 + // - B * y1 + // + (X12 Y11 - X11 Y12) * l1 >= 0 + LengthDbl a = element_from.end.y - element_from.start.y; + LengthDbl b = element_from.start.x - element_from.end.x; + output.coef_x1 = -a; + output.coef_y1 = -b; + output.coef_x2 = a; + output.coef_y2 = b; + output.coef_lambda1 = element_from.end.x * element_from.start.y + - element_from.start.x * element_from.end.y; + output.coef_lambda2 = a * output.point.x + b * output.point.y; + //std::cout << "a " << a << " output.point.x " << output.point.x + // << " prod " << a * output.point.x + // << " b " << b << " output.point.y " << output.point.y + // << " prod " << b * output.point.y << std::endl; + return output; +} + +/** + * Find an edge to separate two given shapes. + * + * The selected edge is the less constraining one. + */ +inline EdgeSeparationConstraintParameters find_best_edge_separator( + const Shape& shape_1, + const Point& shift_1, + double scale_1, + const Shape& shape_2, + const Point& shift_2, + double scale_2) +{ + //std::cout << "compute_edge_separation_constraint_parameters" + // << " shape_1 " << shape_1.elements.size() + // << " shift_1 " << shift_1.to_string() + // << " scale_1 " << scale_1 + // << " shape_2 " << shape_2.elements.size() + // << " shift_2 " << shift_2.to_string() + // << " scale_2 " << scale_2 + // << std::endl; + EdgeSeparationConstraintParameters output; + output.distance = -std::numeric_limits::infinity(); + + for (ElementPos element_1_pos = 0; + element_1_pos < (ElementPos)shape_1.elements.size(); + ++element_1_pos) { + const ShapeElement& element = shape_1.elements[element_1_pos]; + EdgeSeparationConstraintParameters p = compute_edge_separation_constraint_parameters( + shape_1, + shift_1, + scale_1, + element_1_pos, + shape_2, + shift_2, + scale_2); + if (output.distance < p.distance) { + output = p; + output.edge_shape_pos = 0; + output.edge_element_pos = element_1_pos; + } + } + + for (ElementPos element_2_pos = 0; + element_2_pos < (ElementPos)shape_2.elements.size(); + ++element_2_pos) { + const ShapeElement& element = shape_2.elements[element_2_pos]; + EdgeSeparationConstraintParameters p = compute_edge_separation_constraint_parameters( + shape_2, + shift_2, + scale_2, + element_2_pos, + shape_1, + shift_1, + scale_1); + if (output.distance < p.distance) { + std::swap(p.coef_x1, p.coef_x2); + std::swap(p.coef_y1, p.coef_y2); + std::swap(p.coef_lambda1, p.coef_lambda2); + output = p; + output.edge_shape_pos = 1; + output.edge_element_pos = element_2_pos; + } + } + + LengthDbl value + = output.coef_x1 * shift_1.x + + output.coef_y1 * shift_1.y + + output.coef_x2 * shift_2.x + + output.coef_y2 * shift_2.y + + output.coef_lambda1 * scale_1 + + output.coef_lambda2 * scale_2; + //if (shape::strictly_lesser(value, 0.0)) { + if (shape::strictly_lesser(value, -1e-6)) { + const ShapeElement& edge_element = ((output.edge_shape_pos == 0)? + shape_1.elements[output.edge_element_pos]: + shape_2.elements[output.edge_element_pos]); + const ShapeElement& point_element = ((output.edge_shape_pos == 0)? + shape_2.elements[output.point_element_pos]: + shape_1.elements[output.point_element_pos]); + throw std::logic_error( + FUNC_SIGNATURE + ": violated separation constraint; " + "edge_element: " + edge_element.to_string() + "; " + "point_element: " + point_element.to_string() + "; " + "point: " + output.point.to_string() + "; " + "distance: " + std::to_string(output.distance) + "; " + "coef_x1: " + std::to_string(output.coef_x1) + "; " + "coef_y1: " + std::to_string(output.coef_y1) + "; " + "coef_lambda1: " + std::to_string(output.coef_lambda1) + "; " + "coef_x2: " + std::to_string(output.coef_x2) + "; " + "coef_y2: " + std::to_string(output.coef_y2) + "; " + "coef_lambda2: " + std::to_string(output.coef_lambda2) + "; " + "value: " + std::to_string(value) + "."); + } + + return output; +} + } // namespace irregular } // namespace packingsolver diff --git a/test/irregular/linear_programming_test.cpp b/test/irregular/linear_programming_test.cpp index f27a7ab31..7bcfaef25 100644 --- a/test/irregular/linear_programming_test.cpp +++ b/test/irregular/linear_programming_test.cpp @@ -1,5 +1,6 @@ #include "packingsolver/irregular/instance_builder.hpp" -#include "irregular/linear_programming.hpp" +#include "irregular/linear_programming/anchor.hpp" +#include "irregular/utils.hpp" #include "irregular/solution_builder.hpp" #include diff --git a/test/irregular/polygon_test.cpp b/test/irregular/polygon_test.cpp index 39130c2b9..da18a15ae 100644 --- a/test/irregular/polygon_test.cpp +++ b/test/irregular/polygon_test.cpp @@ -1,4 +1,4 @@ -#include "irregular/local_search_direct_trigonometry/polygon.hpp" +#include "irregular/direct_trigonometry/polygon.hpp" #include