diff --git a/data/irregular/tests/feasibility_poly1a_five_items.json b/data/irregular/tests/feasibility_poly1a_five_items.json new file mode 100644 index 000000000..accbc85fa --- /dev/null +++ b/data/irregular/tests/feasibility_poly1a_five_items.json @@ -0,0 +1,447 @@ +{ + "bin_types": [ + { + "copies": 1, + "copies_min": 0, + "cost": 204.49, + "elements": [ + { + "end": { + "x": 14.3, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 14.3, + "y": 14.3 + }, + "start": { + "x": 14.3, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 14.3 + }, + "start": { + "x": 14.3, + "y": 14.3 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 14.3 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "item_bin_minimum_spacing": 0.0, + "type": "general" + } + ], + "item_types": [ + { + "allowed_rotations": [ + { + "end": 0.0, + "mirror": false, + "start": 0.0 + } + ], + "copies": 1, + "profit": 23.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 10.0, + "y": 2.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 8.0, + "y": 5.0 + }, + "start": { + "x": 10.0, + "y": 2.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 4.0, + "y": 4.0 + }, + "start": { + "x": 8.0, + "y": 5.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 4.0, + "y": 4.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 0.0, + "mirror": false, + "start": 0.0 + } + ], + "copies": 1, + "profit": 28.5, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 8.0, + "y": 0.0 + }, + "start": { + "x": 1.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 4.0, + "y": 3.0 + }, + "start": { + "x": 8.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 7.0, + "y": 6.0 + }, + "start": { + "x": 4.0, + "y": 3.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 5.0 + }, + "start": { + "x": 7.0, + "y": 6.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 1.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 5.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 0.0, + "mirror": false, + "start": 0.0 + } + ], + "copies": 1, + "profit": 29.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 6.0, + "y": 2.0 + }, + "start": { + "x": 2.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 9.0, + "y": 1.0 + }, + "start": { + "x": 6.0, + "y": 2.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 7.0, + "y": 3.0 + }, + "start": { + "x": 9.0, + "y": 1.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 3.0, + "y": 5.0 + }, + "start": { + "x": 7.0, + "y": 3.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 5.0, + "y": 7.0 + }, + "start": { + "x": 3.0, + "y": 5.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 8.0 + }, + "start": { + "x": 5.0, + "y": 7.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 2.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 8.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 0.0, + "mirror": false, + "start": 0.0 + } + ], + "copies": 1, + "profit": 25.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 10.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 9.0, + "y": 4.0 + }, + "start": { + "x": 10.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 4.0, + "y": 2.0 + }, + "start": { + "x": 9.0, + "y": 4.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 2.0, + "y": 3.0 + }, + "start": { + "x": 4.0, + "y": 2.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 2.0, + "y": 3.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 0.0, + "mirror": false, + "start": 0.0 + } + ], + "copies": 1, + "profit": 22.5, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 5.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 3.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 7.0, + "y": 2.0 + }, + "start": { + "x": 5.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 8.0, + "y": 4.0 + }, + "start": { + "x": 7.0, + "y": 2.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 2.0, + "y": 5.0 + }, + "start": { + "x": 8.0, + "y": 4.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 3.0 + }, + "start": { + "x": 2.0, + "y": 5.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + } + ], + "objective": "feasibility", + "parameters": { + "item_item_minimum_spacing": 0.0, + "leftover_corner": "BottomLeft", + "open_dimension_xy_aspect_ratio": -1.0 + } +} \ No newline at end of file diff --git a/data/irregular/tests/feasibility_poly2a_five_items_feasible.json b/data/irregular/tests/feasibility_poly2a_five_items_feasible.json new file mode 100644 index 000000000..bf3646a65 --- /dev/null +++ b/data/irregular/tests/feasibility_poly2a_five_items_feasible.json @@ -0,0 +1,489 @@ +{ + "objective": "feasibility", + "parameters": { + "item_item_minimum_spacing": 0.0, + "leftover_corner": "BottomLeft", + "open_dimension_xy_aspect_ratio": -1.0 + }, + "bin_types": [ + { + "copies": 1, + "copies_min": 0, + "cost": 2041755.2100000002, + "elements": [ + { + "end": { + "x": 1428.9, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 1428.9, + "y": 1428.9 + }, + "start": { + "x": 1428.9, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 1428.9 + }, + "start": { + "x": 1428.9, + "y": 1428.9 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 1428.9 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "item_bin_minimum_spacing": 0.0, + "type": "general" + } + ], + "item_types": [ + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 230400.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 1000.0, + "y": 199.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 800.0, + "y": 500.0 + }, + "start": { + "x": 1000.0, + "y": 199.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 400.0, + "y": 400.0 + }, + "start": { + "x": 800.0, + "y": 500.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 400.0, + "y": 400.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 245000.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 700.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 499.0, + "y": 700.0 + }, + "start": { + "x": 700.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 499.0, + "y": 700.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 309550.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 599.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 799.0, + "y": 200.0 + }, + "start": { + "x": 599.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 300.0, + "y": 700.0 + }, + "start": { + "x": 799.0, + "y": 200.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 300.0, + "y": 700.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 284649.5, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 800.0, + "y": 0.0 + }, + "start": { + "x": 99.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 399.0, + "y": 300.0 + }, + "start": { + "x": 800.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 700.0, + "y": 600.0 + }, + "start": { + "x": 399.0, + "y": 300.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 499.0 + }, + "start": { + "x": 700.0, + "y": 600.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 99.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 499.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 289000.5, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 599.0, + "y": 199.0 + }, + "start": { + "x": 200.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 899.0, + "y": 100.0 + }, + "start": { + "x": 599.0, + "y": 199.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 699.0, + "y": 299.0 + }, + "start": { + "x": 899.0, + "y": 100.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 299.0, + "y": 499.0 + }, + "start": { + "x": 699.0, + "y": 299.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 499.0, + "y": 699.0 + }, + "start": { + "x": 299.0, + "y": 499.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 799.0 + }, + "start": { + "x": 499.0, + "y": 699.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 200.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 799.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + } + ] +} \ No newline at end of file diff --git a/data/irregular/tests/feasibility_poly2a_five_items_infeasible.json b/data/irregular/tests/feasibility_poly2a_five_items_infeasible.json new file mode 100644 index 000000000..ba6635b81 --- /dev/null +++ b/data/irregular/tests/feasibility_poly2a_five_items_infeasible.json @@ -0,0 +1,456 @@ +{ + "objective": "feasibility", + "parameters": { + "item_item_minimum_spacing": 0.0, + "leftover_corner": "BottomLeft", + "open_dimension_xy_aspect_ratio": -1.0 + }, + "bin_types": [ + { + "copies": 1, + "copies_min": 0, + "cost": 2041755.2100000002, + "elements": [ + { + "end": { + "x": 1428.9, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 1428.9, + "y": 1428.9 + }, + "start": { + "x": 1428.9, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 1428.9 + }, + "start": { + "x": 1428.9, + "y": 1428.9 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 1428.9 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "item_bin_minimum_spacing": 0.0, + "type": "general" + } + ], + "item_types": [ + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 230400.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 1000.0, + "y": 199.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 800.0, + "y": 500.0 + }, + "start": { + "x": 1000.0, + "y": 199.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 400.0, + "y": 400.0 + }, + "start": { + "x": 800.0, + "y": 500.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 400.0, + "y": 400.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 245000.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 700.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 499.0, + "y": 700.0 + }, + "start": { + "x": 700.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 499.0, + "y": 700.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 370000.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 600.0, + "y": 0.0 + }, + "start": { + "x": 200.0, + "y": 300.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 700.0, + "y": 700.0 + }, + "start": { + "x": 600.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 1000.0 + }, + "start": { + "x": 700.0, + "y": 700.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 200.0, + "y": 300.0 + }, + "start": { + "x": 0.0, + "y": 1000.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 309550.0, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 599.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 799.0, + "y": 200.0 + }, + "start": { + "x": 599.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 300.0, + "y": 700.0 + }, + "start": { + "x": 799.0, + "y": 200.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 0.0 + }, + "start": { + "x": 300.0, + "y": 700.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + }, + { + "allowed_rotations": [ + { + "end": 90.0, + "mirror": false, + "start": 90.0 + }, + { + "end": 180.0, + "mirror": false, + "start": 180.0 + }, + { + "end": 270.0, + "mirror": false, + "start": 270.0 + }, + { + "end": 360.0, + "mirror": false, + "start": 360.0 + } + ], + "copies": 1, + "profit": 284649.5, + "shapes": [ + { + "elements": [ + { + "end": { + "x": 800.0, + "y": 0.0 + }, + "start": { + "x": 99.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 399.0, + "y": 300.0 + }, + "start": { + "x": 800.0, + "y": 0.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 700.0, + "y": 600.0 + }, + "start": { + "x": 399.0, + "y": 300.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 0.0, + "y": 499.0 + }, + "start": { + "x": 700.0, + "y": 600.0 + }, + "type": "LineSegment" + }, + { + "end": { + "x": 99.0, + "y": 0.0 + }, + "start": { + "x": 0.0, + "y": 499.0 + }, + "type": "LineSegment" + } + ], + "is_path": false, + "type": "general" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/img/irregular_benders_decomposition_iteration.svg b/doc/img/irregular_benders_decomposition_iteration.svg new file mode 100644 index 000000000..b96db38a6 --- /dev/null +++ b/doc/img/irregular_benders_decomposition_iteration.svg @@ -0,0 +1,35 @@ + + + + +solve the master problem + + +can its solution beat the best one? + +yes + +no + +stop + +for each bin, add its items, largest first,until MILP NFP proves that they don't fit + + +if none is proven infeasible,pack the items of the bin + + +does every bin fit? + +no + +yes + +stop + +minimal infeasible subsetof each bin which doesn't fit + + +lift the proven cuts,add the cuts to the master problem + + diff --git a/doc/img/irregular_milp_nfp_core_widening.svg b/doc/img/irregular_milp_nfp_core_widening.svg new file mode 100644 index 000000000..ad881900b --- /dev/null +++ b/doc/img/irregular_milp_nfp_core_widening.svg @@ -0,0 +1,20 @@ + + + +core of i + + +i + +j + +k + + + +coreheight + + + +W + diff --git a/doc/img/irregular_milp_nfp_pieces.svg b/doc/img/irregular_milp_nfp_pieces.svg new file mode 100644 index 000000000..3217ea401 --- /dev/null +++ b/doc/img/irregular_milp_nfp_pieces.svg @@ -0,0 +1,33 @@ + + +positions in the bin + + +i + +j + + +p_i +p_j +relative positions d = p_j - p_i + +F1 + +F2 + +F3 + +F4 + +NFP + +R + + +exact fit + +d + +0 + diff --git a/doc/internals/algorithm_selection.rst b/doc/internals/algorithm_selection.rst index f990690bc..16abf2d73 100644 --- a/doc/internals/algorithm_selection.rst +++ b/doc/internals/algorithm_selection.rst @@ -36,7 +36,7 @@ With a single bin, the problem is a single :code:`knapsack`, :code:`feasibility` * :code:`rectangleguillotine`: depending on the number of stages, the cut type and the features used, the :ref:`tree search `, the :ref:`column generation strips `, the :ref:`tree search with maximal spaces `, or the :ref:`tree search hypergraph with infinite copies ` when the item types have many copies; * :code:`box`: the tree search; for the :code:`knapsack` and :code:`feasibility` objectives, only in the directions in which few items fit in a section of the bin (at most 8 on average), or the :ref:`tree search with maximal spaces ` if there is no such direction; * :code:`boxstacks`: the :ref:`sequential one-dimensional / rectangle ` algorithm; -* :code:`irregular`: the tree search, or the :ref:`tree search with periodic packings ` when the instance is dominated by item types with many copies (together with the tree search if fewer than 64 items fit in the bin), and the :ref:`local search ` for the objectives it supports. +* :code:`irregular`: the tree search, or the :ref:`tree search with periodic packings ` when the instance is dominated by item types with many copies (together with the tree search if fewer than 64 items fit in the bin), and the :ref:`local search ` for the objectives it supports; in the :code:`exact` mode, the :ref:`Benders decomposition ` for the :code:`knapsack` objective, and the :ref:`MILP NFP ` algorithm for the :code:`feasibility` objective. Several bins ------------ diff --git a/doc/internals/generic_algorithms/column_generation.rst b/doc/internals/generic_algorithms/column_generation.rst index 495cebb96..c3b3cd76f 100644 --- a/doc/internals/generic_algorithms/column_generation.rst +++ b/doc/internals/generic_algorithms/column_generation.rst @@ -79,7 +79,7 @@ The pricing problems are solved with the regular algorithms of the problem type, **Bound.** The value of the restricted master problem is not a bound until no pattern of negative reduced cost remains, which a heuristic pricing can't prove. But the algorithms of the pricing problem also return a bound on the profit of the best pattern (for example the area of the bin, or a :ref:`dual feasible function ` bound), which bounds the best reduced cost :math:`\bar{r}` of a pattern of each bin type. Since a solution uses at most :math:`N` bins, the value of the linear relaxation is at least the value of the restricted master problem plus :math:`N \bar{r}`: this *Lagrangian bound* is valid at each iteration. :math:`N` is the number of items or of bins, whichever is smaller; for the :code:`bin-packing` objective, the number of bins of the best solution found; for the :code:`variable-sized-bin-packing` objective, the largest number of bins whose cost doesn't exceed the cost of the best solution found. -**Exact pricing for rectangle.** For the rectangle problem type, once the column generation converges with the regular pricing, the pricing problems are solved once more with the :ref:`Benders decomposition ` (at most twice per column generation), which returns a much tighter bound on the best pattern, and proves the bound of the linear relaxation when it is exact. In the :code:`exact` mode, this Benders decomposition is itself run in :code:`exact` mode. +**Exact pricing for rectangle and irregular.** For the rectangle and irregular problem types, once the column generation converges with the regular pricing, the pricing problems are solved once more with the Benders decomposition (:ref:`rectangle `, :ref:`irregular `, with the :ref:`MILP NFP ` algorithm in its subproblems) (at most twice per column generation), which returns a much tighter bound on the best pattern, and proves the bound of the linear relaxation when it is exact. In the :code:`exact` mode, this Benders decomposition is itself run in :code:`exact` mode. Search ------ diff --git a/doc/internals/irregular.rst b/doc/internals/irregular.rst index f9579ba1f..634e5ed81 100644 --- a/doc/internals/irregular.rst +++ b/doc/internals/irregular.rst @@ -74,6 +74,24 @@ It rasterizes the bins and the items onto a grid and solves the resulting placem See :doc:`the detailed description `. +Benders decomposition +------------------------ + +This algorithm solves the :code:`knapsack`, :code:`bin-packing` and :code:`variable-sized-bin-packing` objectives. + +Its master problem assigns the items to the bins considering only their areas, as a one-dimensional problem. For each bin of its solution, a subproblem checks whether the items actually fit; if not, no-good cuts forbidding infeasible subsets of them are added to the master problem, which is solved again. With the :ref:`MILP NFP ` algorithm in its subproblems, the cuts are proven, so the value of the master problem is a bound, and the algorithm is exact. + +See :doc:`the detailed description `. + +MILP NFP +------------ + +This algorithm solves the :code:`feasibility` objective with a single bin. Its main use is to prove that a set of items doesn't fit in a bin, in the subproblems of the Benders decomposition. + +For each combination of rotations of the items, the non-overlap of each pair of items is modeled with the convex pieces of the complement of their no-fit polygon, in a mixed-integer linear program. The items don't fit if every program is infeasible. + +See :doc:`the detailed description `. + One-dimensional bound ------------------------ @@ -90,3 +108,5 @@ Relaxes the instance to a one-dimensional problem (each bin and item type keeps irregular/tree_search_maximal_spaces irregular/local_search irregular/milp_raster + irregular/benders_decomposition + irregular/milp_nfp diff --git a/doc/internals/irregular/benders_decomposition.rst b/doc/internals/irregular/benders_decomposition.rst new file mode 100644 index 000000000..ad8691b16 --- /dev/null +++ b/doc/internals/irregular/benders_decomposition.rst @@ -0,0 +1,112 @@ +.. _internals_irregular_benders_decomposition: + +Benders decomposition +===================== + +Objectives +---------- + +This algorithm solves the :code:`knapsack` objective, with one or several bins, and the :code:`bin-packing` and :code:`variable-sized-bin-packing` objectives. It supports the resources of the bins. + +It is an exact method when its subproblems use the :ref:`MILP NFP ` algorithm: when it converges, the solution found is optimal, and before that, the value of its master problem is a bound. + +Principle +--------- + +It is the combinatorial Benders decomposition of the :ref:`rectangle Benders decomposition `, with the geometry of irregular items. The problem is split in two: + +* the *master problem* decides which items go in which bin, ignoring the geometry: it is a one-dimensional problem, where each item is reduced to its area and each bin to its area; +* the *subproblems* check, for each bin of the solution of the master problem, whether its items actually fit together in the bin. + +When the items of a bin don't fit, *no-good cuts* are added to the master problem, forbidding infeasible subsets of them in a bin of this type, and the master problem is solved again. Since the master problem is a relaxation of the problem, the value of its optimal solution is a bound. The algorithm stops when the items of every bin fit, or when the solution of the master problem can't be better than the best solution found: the best solution found is then optimal. + +Unlike in the rectangle version, nothing is known about the geometry before the first iteration: two irregular items which don't fit side by side or one above the other may still fit together, interlocked or rotated, so there are no incompatible pairs or triplets, and no dual feasible function cuts. All the geometric information of the master problem comes from the subproblems. + +Master problem +-------------- + +The master problem is a :ref:`onedimensional ` instance, with the objective of the instance: + +* each bin type has its area, rounded up, as length, and keeps its copies, its cost and its resources; +* each item type has its area, rounded down, as length, and keeps its copies and, for the :code:`knapsack` objective, its profit. + +The roundings keep the master problem a relaxation. It is solved with the :ref:`MILP assignment ` algorithm, in non-anytime mode, or in :code:`exact` mode in the :code:`exact` mode. + +The cuts are encoded as onedimensional *resources* on the bin types, as in the rectangle version: a cut forbidding :math:`n_i` copies of each item type :math:`i` of a set :math:`S`, with lifted item types :math:`L`, is the resource of capacity :math:`\sum_{i \in S} n_i - 1` where the copies of item type :math:`i \in S` consume :math:`(1, \ldots, 1, 0)` (:math:`n_i` ones) and the copies of item type :math:`j \in L` consume :math:`(1, 0)`. With the variables :math:`x_{i,t,k,c}` of the MILP assignment model (bin :math:`k` of type :math:`t` contains at least :math:`c` copies of item type :math:`i`), it is the constraint, for each bin :math:`(t, k)`: + +.. math:: + + \sum_{i \in S} \sum_{c \le n_i} x_{i,t,k,c} + \sum_{j \in L} x_{j,t,k,1} \le \sum_{i \in S} n_i - 1 + +Iterations +---------- + +At each iteration, the master problem is solved, then the bins of its solution are checked. With the MILP NFP algorithm in the subproblems: + +.. image:: ../../img/irregular_benders_decomposition_iteration.svg + :align: center + +The steps are: + +1. **Master problem.** If all the cuts are proven (see below), the value of its solution is reported as a bound of the instance. If a solution has already been found, and the solution of the master problem can't be better (smaller profit for the :code:`knapsack` objective, as many bins or more for the :code:`bin-packing` objective, cost as large or larger for the :code:`variable-sized-bin-packing` objective), the algorithm stops. +2. **Subproblems.** The selection of items of each bin of the solution of the master problem is checked (see below). A selection containing the items of a cut added earlier in the same iteration, for another bin, is known to be infeasible and is skipped. The bins whose items fit are assembled into a solution, which is reported if it is better than the best one (for the :code:`knapsack` objective, a subset of the bins is a feasible solution). +3. **Convergence.** If every bin fits, the solution of the master problem is feasible, and the algorithm stops. Otherwise, no-good cuts are added for the bins which don't fit, and the master problem is solved again. + +Subproblems +----------- + +Without the MILP NFP algorithm, the items of a bin are packed by solving a single-bin instance with the :code:`feasibility` objective with the irregular algorithms, in non-anytime mode (a queue of size 128 for the tree search). This finds packings, but it rarely proves that the items don't fit, so the cuts are mostly unproven. + +With the :ref:`MILP NFP ` algorithm: + +* **Infeasible prefix.** The items of the bin are sorted by decreasing area, and the MILP NFP algorithm is called on the largest one, then on the two largest ones, and so on, until it proves that they don't fit. Proving it for a few large items is often much cheaper than for all the items of the bin, and a small infeasible subset is what the cuts need anyway. If the MILP NFP algorithm is inconclusive (time limit, continuous rotations), the search stops. +* **Packing.** If no prefix is proven infeasible, the MILP NFP algorithm is called on all the items of the bin. If its relaxation is feasible, the positions of its solution are checked, and used as a packing if the items don't overlap. Otherwise, the single-bin :code:`feasibility` instance is solved, as above. + +The answers of the MILP NFP algorithm are stored, so that the same selection of items is never checked twice, and the data of the MILP NFP algorithm (the convex pieces of the pairs of item types, the infeasible rotation combinations) are shared by all its calls. + +No-good cuts +------------ + +**Minimal infeasible subsets.** The infeasible items of a bin (the infeasible prefix, or all the items of the bin) are reduced to a minimal infeasible subset with the depth-first search of the rectangle version: the items are sorted by increasing area, and removed one at a time, as long as the remaining items don't fit. Each check is a subproblem, which is expensive for irregular items, so the search stops after a single subset per bin by default. The subset gives a no-good cut: no bin of this type contains at least these copies of these item types. + +**Lifting.** A proven cut forbidding a set :math:`S` of items is lifted by giving a coefficient 1 to other item types: the cut then forbids any :math:`|S|` items among :math:`S` and the lifted item types. The item types not in the cut are visited by decreasing area. An item type :math:`j` is lifted if every selection made of one copy of :math:`j` and of :math:`|S| - 1` items among :math:`S` and the item types already lifted (:math:`L`) is proven infeasible, either because it contains the items of a proven cut, or by the MILP NFP algorithm. Then no feasible selection reaches :math:`|S|` on the lifted cut, so it stays valid. Unlike in the rectangle version, the coefficients are only 0 or 1: there is no cheap bound, like the bar relaxation, on the number of items of the cut which fit together with :math:`j`. At most 4 item types are lifted in a cut. + +Lifting makes each cut much stronger, but it is expensive: on :code:`jakobs2_sb`, it adds about 3 item types per cut, but it takes 60% of the time. + +**Proofs.** A cut is *proven* if every check of its derivation proved that the items don't fit, which in practice requires the MILP NFP algorithm. A cut which isn't proven is still added, so that the algorithm keeps converging, but then the master problem may not be a relaxation anymore: while a cut is unproven, the value of the master problem is not reported as a bound of the instance, and the solution found is not proven optimal. + +Search parameters +----------------- + +In anytime mode, the algorithm runs until it converges or reaches the time limit. In the non-anytime modes, it also stops after 32 iterations. In the :code:`exact` mode, it runs as in anytime mode, its master problem is solved in :code:`exact` mode, and its subproblems always use the MILP NFP algorithm, so that its bound is proven. + +Automatic selection +------------------- + +In the :code:`exact` mode, it is run for the :code:`knapsack` objective with a single bin, alongside the other algorithms. The :ref:`column generation ` algorithm uses it, with the MILP NFP algorithm, to solve its pricing problems when it needs to prove a bound. + +It can be selected with :code:`--use-benders-decomposition 1` (CLI) or :code:`use_benders_decomposition` (Python), and its subproblems use the MILP NFP algorithm with :code:`--benders-decomposition-use-milp-nfp 1`. It only finds a solution once every bin of the solution of its master problem is packed, which may take long, while its bound may be good much earlier: it is best run together with other algorithms (e.g. :code:`--use-tree-search 1`), whose solutions may then be proven optimal by this bound. + +Strengths and limitations +------------------------- + +The algorithm proves the optimality of the instances in which few items fit in a bin, or with few item types, whose minimal infeasible subsets are small and shared by many selections. With the tree search, in the :code:`exact` mode, on the :code:`bin-packing` instances of :code:`data/irregular/martinez2017`, it proves the optimality of :code:`albano_sb`, :code:`dighe1_sb`, :code:`dighe2_sb`, :code:`fu_sb`, :code:`han_sb`, :code:`jakobs1_sb`, :code:`mao_sb`, :code:`poly1a_sb`, :code:`shapes0_sb`, :code:`shapes1_sb` and :code:`shapes2_sb`, in a few seconds to a few minutes. + +When more items fit in a bin, the minimal infeasible subsets have 5 items or more, and the MILP NFP algorithm takes seconds to prove each of them: on :code:`poly2a_sb` (15 item types), the bound stays at the area bound. + +Source files +------------ + +* :code:`src/irregular/benders_decomposition.hpp`, :code:`src/irregular/benders_decomposition.cpp`: the decomposition +* :code:`src/irregular/milp_nfp.hpp`, :code:`src/irregular/milp_nfp.cpp`: the MILP NFP algorithm of the subproblems +* :code:`scripts/doc_figures/irregular_benders_decomposition.py`: the figures of this page + +References: + +* "Combinatorial Benders Decomposition for the Two-Dimensional Bin Packing Problem" (Côté, Haouari and Iori, 2021) + + * https://doi.org/10.1287/ijoc.2020.1014 + +* "Facets of the knapsack polytope" (Balas, 1975) + + * https://doi.org/10.1007/BF01580430 diff --git a/doc/internals/irregular/milp_nfp.rst b/doc/internals/irregular/milp_nfp.rst new file mode 100644 index 000000000..280bb41e9 --- /dev/null +++ b/doc/internals/irregular/milp_nfp.rst @@ -0,0 +1,134 @@ +.. _internals_irregular_milp_nfp: + +MILP NFP +======== + +Objectives +---------- + +Given a bin type and a set of items, this algorithm tries to prove that the items don't fit in a bin of this type. It is used in the subproblems of the :ref:`Benders decomposition `. + +It also solves the :code:`feasibility` objective with a single bin. If it doesn't prove that the instance is infeasible, the positions of the solution of its relaxation are checked, and used as a solution if the items don't overlap. + +It returns *infeasible* (proven), *feasible* (the relaxation is feasible, so the items may fit), or *unknown* (time limit, or an item type with a continuous rotation range). + +Principle +--------- + +The rotations of the items are enumerated. For a given rotation of each item, the positions of two items which don't overlap are described exactly by their *no-fit polygon*: item :math:`j` overlaps item :math:`i` if and only if the relative position :math:`p_j - p_i` of their reference points is in the interior of the no-fit polygon :math:`\text{NFP}_{ij}`. The complement of the no-fit polygon is not convex, so it is partitioned into convex pieces, and a binary variable selects the piece containing the relative position: this is the mixed-integer linear program (MILP) of Fischetti and Luzzi (2009), with the bounding box of the bin instead of a strip. + +In the example below, item :math:`i` is a 4 × 3 rectangle with a 1 × 2 notch, item :math:`j` a 1 × 2 rectangle, and the bin is 8 × 6. The relative positions allowed by the bin form the rectangle :math:`R`. The no-fit polygon covers its middle, and the region outside of it is partitioned into the convex pieces :math:`F_1` to :math:`F_4`. Item :math:`j` also fits exactly in the notch: its relative positions there form a segment inside the no-fit polygon, an additional piece (see *Exact fits* below): + +.. image:: ../../img/irregular_milp_nfp_pieces.svg + :align: center + +The items don't fit if the program of every rotation combination is infeasible. The programs of the rotation combinations are independent, so they are solved in parallel (4 threads by default), and the search stops as soon as one of them is feasible. A single program in which binary variables select the rotations was tried, but its linear relaxation is much weaker and it was several times slower. + +The model is a relaxation, so that an infeasible program is a proof: + +* the bin is replaced by its bounding box; the defects, the fixed items and the item-item spacing are ignored; +* the circular arcs of the regions below are approximated by line segments outside of them. + +Model +----- + +**Input**, for a rotation combination: + +* the items :math:`i = 1, \ldots, n`, each with its rotation; +* for each item :math:`i`, its *inner-fit rectangle* :math:`\text{IFP}_i`: the positions of its reference point for which its bounding box is in the bounding box of the bin (minus the item-bin spacing); +* for each pair of items :math:`(i, j)`, the region :math:`R_{ij} = \text{IFP}_j - \text{IFP}_i` of the relative positions allowed by the inner-fit rectangles, and the region :math:`F_{ij} = R_{ij} \setminus \text{int}(\text{NFP}_{ij})` of the ones for which the items don't overlap, partitioned into convex pieces :math:`k \in K_{ij}`. Each piece is described by its edges :math:`(n, c)`, the half-planes :math:`n \cdot d \ge c`. + +**Variables**: + +* :math:`p_i \in \text{IFP}_i`: the position of the reference point of item :math:`i` +* :math:`z^{ij}_k \in \{0, 1\}`, :math:`k \in K_{ij}`: :math:`z^{ij}_k = 1` iff the relative position of items :math:`i` and :math:`j` is in piece :math:`k` + +There is no objective: only the feasibility of the program matters. + +**Constraints**: + +* Piece selection: the relative position of each pair of items is in one of the pieces. + +.. math:: + + \forall (i, j) \qquad \sum_{k \in K_{ij}} z^{ij}_k = 1 + +* Pieces: the edges of a piece are relaxed with big-M coefficients when the piece isn't selected. + +.. math:: + + \forall (i, j), \; \forall k \in K_{ij}, \; \forall \text{ edge } (n, c) \text{ of } k \qquad n \cdot (p_j - p_i) \ge c - M (1 - z^{ij}_k) + +where :math:`M = c - \min_{d \in R_{ij}} n \cdot d` is the smallest value for which the constraint is always satisfied in :math:`R_{ij}`. + +* Symmetry breaking: identical items with the same rotation are sorted by :math:`x`. + +**Exact fits.** An item may fit exactly in a notch of another one, or two items may touch along a whole edge: the relative position is then on a line segment or at a point strictly inside the no-fit polygon, but on no edge of the region :math:`F_{ij}`. These feasible positions of null area are returned by the no-fit polygon computation, and each one is an additional convex piece of :math:`F_{ij}`, so that the program stays a relaxation. + +Rotation combinations +--------------------- + +The rotation combinations are enumerated item by item. Some of them are never solved: + +* **Identical rotations.** Two rotations of an item type which give the same shape (for example, the rotations by 0 and 180 degrees of a rectangle) are only considered once. +* **Identical items.** The rotations of identical items are non-decreasing. +* **Symmetry of the bin.** The program only considers the bounding box of the bin, so turning a solution by 180 degrees gives another solution. If every rotation of every item type has its counterpart turned by 180 degrees, then an item, the only copy of its item type, is restricted to one rotation of each such pair. +* **Pairs.** A partial combination in which the region :math:`F_{ij}` of a pair of items is empty isn't extended. + +Before solving the program of a rotation combination: + +1. **Core widening.** A cheap area test may prove it infeasible (see below). +2. **Sub-combinations.** Its sub-combinations without one of the items are checked first: if one of them is infeasible, so is the combination. Their programs are cheaper, and each of them is shared by several combinations. + +The statuses of the combinations and of the sub-combinations are cached, as well as the convex pieces of the pairs of item types, so that the next calls on other sets of items reuse them. On the 5 items of :code:`data/irregular/tests/feasibility_poly2a_five_items_infeasible.json`, 406 of the 512 rotation combinations are proven infeasible by a sub-combination, and the proof goes from 17.6 to 13 seconds. + +Core widening +------------- + +The *core* of an item is the part of its :math:`y`-range that no other item can reach, given the regions :math:`F_{ij}` (each piece is convex, so its :math:`y`-range gives exactly the heights at which the other item can be). Since the rotations are fixed, no other item has any point in the horizontal band of the core of an item, across the whole bin. So the item can be counted as widened to the width :math:`W` of the bin on its core: + +.. math:: + + \text{widened area}(i) = W \times \text{core height}(i) + \text{area of } i \text{ outside of its core} + +In the example below, items :math:`j` and :math:`k` can't be lower than the top of the foot of item :math:`i`, so the band of the foot belongs to item :math:`i` alone, across the whole bin: + +.. image:: ../../img/irregular_milp_nfp_core_widening.svg + :align: center + +The cores of different items are disjoint, so the rotation combination is infeasible if the sum of the widened areas exceeds the area of the bin. + +This is not a reduction: the parts of an item outside of its core may be interlocked with other items, so the item can't always be moved against a side of the bin to actually be widened. The test helps when the items are large compared to the bin; when they fill less than about three quarters of it, the cores are usually empty. + +Search parameters +----------------- + +The programs are solved with HiGHS, with 4 threads by default, until the time limit. When the algorithm is run on its own, in the :code:`not-anytime-sequential` mode, a single thread is used. + +Automatic selection +------------------- + +In the :code:`exact` mode, it is run for the :code:`feasibility` objective with a single bin, alongside the other algorithms. It is always used in the subproblems of the :ref:`Benders decomposition ` in the :code:`exact` mode. + +It can be selected with :code:`--use-milp-nfp 1` (CLI) or :code:`use_milp_nfp` (Python), for the :code:`feasibility` objective with a single bin only. + +Strengths and limitations +------------------------- + +The number of rotation combinations grows exponentially with the number of items, and the programs get harder as the items get smaller compared to the bin, since the regions :math:`F_{ij}` then have more pieces. The algorithm proves in a fraction of a second that 2 or 3 large items don't fit; for 5 items with 4 rotations each, a proof may take 10 to 20 seconds. + +Source files +------------ + +* :code:`src/irregular/milp_nfp.hpp`, :code:`src/irregular/milp_nfp.cpp`: the algorithm +* :code:`scripts/doc_figures/irregular_milp_nfp.py`: the figures of this page + +References: + +* "Mixed-integer programming models for nesting problems" (Fischetti and Luzzi, 2009) + + * https://doi.org/10.1007/s10732-008-9088-9 + +* "A branch & bound algorithm for cutting and packing irregularly shaped pieces" (Alvarez-Valdes, Martinez and Tamarit, 2013) + + * https://doi.org/10.1016/j.ijpe.2013.04.007 diff --git a/include/packingsolver/irregular/instance.hpp b/include/packingsolver/irregular/instance.hpp index 0a4bd6973..8a98d4413 100644 --- a/include/packingsolver/irregular/instance.hpp +++ b/include/packingsolver/irregular/instance.hpp @@ -439,6 +439,15 @@ class Instance /** Get the objective of the problem. */ inline Objective objective() const { return objective_; } + /** + * Get the knapsack goal: for the 'Knapsack' objective, the search stops + * as soon as a solution reaches it, or as soon as the bound proves that + * it can't be reached (e.g. a pricing problem of a column generation, + * which only needs a column of negative reduced cost, or a proof that + * there is none). Infinite by default. + */ + inline Profit knapsack_goal() const { return knapsack_goal_; } + /* * Getters: parameters */ @@ -641,6 +650,9 @@ class Instance /** Objective. */ Objective objective_ = Objective::BinPacking; + /** Knapsack goal. */ + Profit knapsack_goal_ = std::numeric_limits::infinity(); + /** Parameters. */ Parameters parameters_; diff --git a/include/packingsolver/irregular/instance_builder.hpp b/include/packingsolver/irregular/instance_builder.hpp index c94783a2e..608f46521 100644 --- a/include/packingsolver/irregular/instance_builder.hpp +++ b/include/packingsolver/irregular/instance_builder.hpp @@ -18,6 +18,9 @@ class InstanceBuilder /** Set the objective. */ void set_objective(Objective objective) { instance_.objective_ = objective; } + /** Set the knapsack goal (see 'Instance::knapsack_goal'). */ + void set_knapsack_goal(Profit knapsack_goal) { instance_.knapsack_goal_ = knapsack_goal; } + /* * Read from files */ diff --git a/include/packingsolver/irregular/optimize.hpp b/include/packingsolver/irregular/optimize.hpp index 2fff3713c..e9df4a0ab 100644 --- a/include/packingsolver/irregular/optimize.hpp +++ b/include/packingsolver/irregular/optimize.hpp @@ -82,9 +82,15 @@ struct Output: packingsolver::Output if (is_proven_infeasible) return true; switch (solution_pool.best().instance().objective()) { - case Objective::Knapsack: + case Objective::Knapsack: { + Profit knapsack_goal = solution_pool.best().instance().knapsack_goal(); + // The bound proves that the knapsack goal can't be reached. + if (std::isfinite(knapsack_goal) && knapsack_bound < knapsack_goal) + return true; return solution_pool.best().feasible() - && equal_profit(knapsack_bound, solution_pool.best().profit()); + && (equal_profit(knapsack_bound, solution_pool.best().profit()) + || solution_pool.best().profit() >= knapsack_goal); + } case Objective::BinPacking: return solution_pool.best().feasible() && bin_packing_bound == solution_pool.best().number_of_bins(); @@ -257,6 +263,28 @@ struct OptimizeParameters: packingsolver::Parameters /** Use column generation algorithm. */ bool use_column_generation = false; + /** + * Use Benders decomposition algorithm (only for the 'Knapsack', + * 'BinPacking' and 'VariableSizedBinPacking' objectives; only selected + * automatically in 'Exact' mode, for the 'Knapsack' objective with a + * single bin). + */ + bool use_benders_decomposition = false; + + /** + * Use the MILP NFP algorithm in the subproblems of the Benders + * decomposition algorithm, to prove that the items of a bin don't fit. + * + * Always used in 'Exact' mode. + */ + bool benders_decomposition_use_milp_nfp = false; + + /** + * Use the MILP NFP algorithm (only for the 'Feasibility' objective with a + * single bin; only selected automatically in 'Exact' mode). + */ + bool use_milp_nfp = false; + /** Initial maximum approximation ratio. */ double initial_maximum_approximation_ratio = 0.20; @@ -339,6 +367,12 @@ struct OptimizeParameters: packingsolver::Parameters */ NodeId column_generation_subproblem_tree_search_queue_size = 128; + /** + * Size of the queue for the feasibility subproblem of the Benders + * decomposition algorithm. + */ + NodeId benders_decomposition_subproblem_tree_search_queue_size = 128; + /* * Parameters for anytime mode */ @@ -413,6 +447,9 @@ struct OptimizeParameters: packingsolver::Parameters /** Number of iterations of the sequential value correction algorithm. */ Counter not_anytime_sequential_value_correction_number_of_iterations = 32; + /** Number of iterations of the Benders decomposition algorithm. */ + Counter not_anytime_benders_decomposition_number_of_iterations = 32; + /** * Maximum number of failed separations of the local search, after which * a sub-problem is considered infeasible. diff --git a/python/src/irregular.cpp b/python/src/irregular.cpp index afb66a255..e3f65ad11 100644 --- a/python/src/irregular.cpp +++ b/python/src/irregular.cpp @@ -667,6 +667,9 @@ void bind_irregular(nb::module_& m) .def_rw("use_local_search_direct_trigonometry", &OptimizeParameters::use_local_search_direct_trigonometry) .def_rw("use_local_search_black_box_optimization", &OptimizeParameters::use_local_search_black_box_optimization) .def_rw("use_milp_raster", &OptimizeParameters::use_milp_raster) + .def_rw("use_milp_nfp", &OptimizeParameters::use_milp_nfp) + .def_rw("use_benders_decomposition", &OptimizeParameters::use_benders_decomposition) + .def_rw("benders_decomposition_use_milp_nfp", &OptimizeParameters::benders_decomposition_use_milp_nfp) .def_rw("use_sequential_single_knapsack", &OptimizeParameters::use_sequential_single_knapsack) .def_rw("use_sequential_value_correction", &OptimizeParameters::use_sequential_value_correction) .def_rw("use_dichotomic_search", &OptimizeParameters::use_dichotomic_search) diff --git a/scripts/doc_figures/irregular_benders_decomposition.py b/scripts/doc_figures/irregular_benders_decomposition.py new file mode 100644 index 000000000..98f0b7bd6 --- /dev/null +++ b/scripts/doc_figures/irregular_benders_decomposition.py @@ -0,0 +1,61 @@ +"""Figures of the detailed description of the Benders decomposition of +irregular. + +Usage, from the root of the repository: + + python3 scripts/doc_figures/irregular_benders_decomposition.py +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import figure +from figure import BLUE, RED, YELLOW + +SVG_DIR = "doc/img" +PREFIX = "irregular_benders_decomposition_" + + +def figure_iteration(): + """Flow of an iteration, with the MILP NFP algorithm in the + subproblems.""" + fig = figure.Figure(unit=30) + bw, bh = 11, 1.2 + step = 2.0 + + steps = [ + ("solve the master problem", BLUE, None), + ("can its solution beat the best one?", YELLOW, ("no", "stop")), + ("for each bin, add its items, largest first,\nuntil MILP NFP proves that they don't fit", BLUE, None), + ("if none is proven infeasible,\npack the items of the bin", BLUE, None), + ("does every bin fit?", YELLOW, ("yes", "stop")), + ("minimal infeasible subset\nof each bin which doesn't fit", BLUE, None), + ("lift the proven cuts,\nadd the cuts to the master problem", BLUE, None), + ] + x = 0 + for k, (label, style, side) in enumerate(steps): + y = -k * step + fig.rect(x - bw / 2, y - bh / 2, bw, bh, label, style + "rounded=1;fontSize=11;") + if k + 1 < len(steps): + fig.arrow(x, y - bh / 2, x, y - step + bh / 2, "strokeColor=#333333;") + if style == YELLOW: + answer = "yes" if side[0] == "no" else "no" + fig.text(x + 0.3, y - step / 2, answer, w=1, size=11, align="left") + if side is not None: + answer, action = side + fig.arrow(x + bw / 2, y, x + bw / 2 + 2, y, "strokeColor=#333333;") + fig.text(x + bw / 2 + 1, y + 0.35, answer, w=1.5, size=11) + fig.rect(x + bw / 2 + 2, y - bh / 2, 2.4, bh, action, RED + "rounded=1;fontSize=11;") + + # Back to the master problem. + y_last = -(len(steps) - 1) * step + fig.polyline( + [(x - bw / 2, y_last), (x - bw / 2 - 1, y_last), (x - bw / 2 - 1, 0), (x - bw / 2, 0)], + "strokeColor=#333333;", arrow=True) + + fig.write(os.path.join(SVG_DIR, PREFIX + "iteration.svg")) + + +if __name__ == "__main__": + figure_iteration() diff --git a/scripts/doc_figures/irregular_milp_nfp.py b/scripts/doc_figures/irregular_milp_nfp.py new file mode 100644 index 000000000..63a6966df --- /dev/null +++ b/scripts/doc_figures/irregular_milp_nfp.py @@ -0,0 +1,124 @@ +"""Figures of the detailed description of the MILP NFP algorithm of +irregular. + +Usage, from the root of the repository: + + python3 scripts/doc_figures/irregular_milp_nfp.py +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import figure +from figure import BLUE, GREEN, YELLOW, NONE + +SVG_DIR = "doc/img" +PREFIX = "irregular_milp_nfp_" + +DARK_GRAY = "fillColor=#cccccc;strokeColor=#666666;" +DOT = "fillColor=#000000;strokeColor=#000000;ellipse;" +RED_STROKE = "#b85450" + + +def dot(fig, x, y, r=0.08): + fig.rect(x - r, y - r, 2 * r, 2 * r, "", DOT) + + +def u_shape(x, y): + """Item i: a 4 x 3 rectangle with a 1 x 2 notch on its top side.""" + return [ + (x, y), (x + 4, y), (x + 4, y + 3), (x + 2.5, y + 3), + (x + 2.5, y + 1), (x + 1.5, y + 1), (x + 1.5, y + 3), (x, y + 3)] + + +def figure_pieces(): + """No-fit polygon of a U-shaped item and of a 1 x 2 rectangle, and the + convex pieces of the region outside of it. + + Bin 8 x 6. The inner-fit rectangles are [0, 4] x [0, 3] for the U and + [0, 7] x [0, 4] for the rectangle, so R = [-4, 7] x [-3, 4]. The no-fit + polygon is [-1, 4] x [-2, 3], with a slit at x = 1.5, 1 <= y <= 3: the + rectangle slides exactly into the notch. + """ + fig = figure.Figure(unit=28) + + # Left: a packing in which the rectangle is exactly in the notch. + fig.text(4, 7, "positions in the bin", w=8) + fig.bin(0, 0, 8, 6) + pi = (1, 1) + pj = (2.5, 2) + fig.polygon(u_shape(*pi), "i", BLUE, label_position=(pi[0] + 0.75, pi[1] + 1.8)) + fig.rect(pj[0], pj[1], 1, 2, "j", GREEN) + dot(fig, *pi) + dot(fig, *pj) + fig.text(pi[0] - 0.2, pi[1] - 0.35, "p_i", w=1, size=11, align="right") + fig.text(pj[0] + 0.15, pj[1] - 0.35, "p_j", w=1, size=11, align="left") + + # Right: the relative positions d = p_j - p_i. + ox, oy = 15, 3 + fig.text(ox + 1.5, oy + 5, "relative positions d = p_j - p_i", w=11) + # Convex pieces of F = R \ int(NFP). + pieces = [ + ((-4, -3), 3, 7, "F1"), + ((4, -3), 3, 7, "F2"), + ((-1, -3), 5, 1, "F3"), + ((-1, 3), 5, 1, "F4"), + ] + for (x, y), w, h, label in pieces: + fig.rect(ox + x, oy + y, w, h, label, GREEN) + # No-fit polygon. + fig.rect(ox - 1, oy - 2, 5, 5, "", DARK_GRAY) + fig.text(ox + 3.0, oy - 1.3, "NFP", w=2, size=13) + # R. + fig.rect(ox - 4, oy - 3, 11, 7, "", NONE + "strokeWidth=2;dashed=1;") + fig.text(ox + 7.2, oy + 3.7, "R", w=1, size=13, align="left") + # Exact fit: the slit of the no-fit polygon. + fig.polyline([(ox + 1.5, oy + 1), (ox + 1.5, oy + 3)], + "strokeColor={};strokeWidth=4;".format(RED_STROKE)) + fig.polyline([(ox + 2.35, oy + 2.2), (ox + 1.6, oy + 2.2)], + "strokeColor={};".format(RED_STROKE)) + fig.text(ox + 2.4, oy + 2.2, "exact fit", w=3, size=11, align="left", + extra="fontColor={};".format(RED_STROKE)) + # The relative position of the packing on the left. + dot(fig, ox + pj[0] - pi[0], oy + pj[1] - pi[1]) + fig.text(ox + 1.3, oy + 0.75, "d", w=1, size=11, align="right") + # Origin. + dot(fig, ox, oy, r=0.06) + fig.text(ox - 0.15, oy - 0.3, "0", w=1, size=11, align="right") + + fig.write(os.path.join(SVG_DIR, PREFIX + "pieces.svg")) + + +def figure_core_widening(): + """Core of an item: a horizontal band across the bin which no other item + can reach.""" + fig = figure.Figure(unit=30) + W, H = 10, 5 + core = 1.5 + + fig.rect(0, 0, W, core, "", YELLOW + "dashed=1;opacity=60;") + fig.text(W - 0.2, core / 2, "core of i", w=3, size=11, align="right") + fig.bin(0, 0, W, H) + fig.polygon([(0.5, 0), (4, 0), (4, 1.5), (2, 1.5), (2, 3.5), (0.5, 3.5)], "i", BLUE, + label_position=(1.25, 2.5)) + fig.polygon([(4.5, 1.8), (7, 1.8), (7, 4.6), (5.5, 4.6), (5.5, 3), (4.5, 3)], "j", GREEN, + label_position=(6.25, 3.2)) + fig.polygon([(7.5, 1.6), (9.8, 1.6), (9.8, 4.8)], "k", GREEN, label_position=(9.1, 2.4)) + # Height of the core. + fig.polyline([(-0.4, 0), (-0.4, core)]) + fig.polyline([(-0.55, 0), (-0.25, 0)]) + fig.polyline([(-0.55, core), (-0.25, core)]) + fig.text(-0.6, core / 2, "core\nheight", w=2, size=11, align="right") + # Width of the bin. + fig.polyline([(0, -0.4), (W, -0.4)]) + fig.polyline([(0, -0.55), (0, -0.25)]) + fig.polyline([(W, -0.55), (W, -0.25)]) + fig.text(W / 2, -0.75, "W", w=1, size=11) + + fig.write(os.path.join(SVG_DIR, PREFIX + "core_widening.svg")) + + +if __name__ == "__main__": + figure_pieces() + figure_core_widening() diff --git a/src/algorithms/column_generation.hpp b/src/algorithms/column_generation.hpp index 2c7fc8b66..f4d44a705 100644 --- a/src/algorithms/column_generation.hpp +++ b/src/algorithms/column_generation.hpp @@ -675,11 +675,13 @@ PricingOutput ColumnGenerationPricingSolver::infinity(); if (instance_.objective() == Objective::VariableSizedBinPacking || instance_.objective() == Objective::BinPacking) { diff --git a/src/irregular/CMakeLists.txt b/src/irregular/CMakeLists.txt index e897e6ecc..b751d9ada 100644 --- a/src/irregular/CMakeLists.txt +++ b/src/irregular/CMakeLists.txt @@ -25,6 +25,8 @@ target_sources(PackingSolver_irregular PRIVATE nonlinear_programming/separation_model.cpp nonlinear_programming/separator.cpp milp_raster.cpp + milp_nfp.cpp + benders_decomposition.cpp trivial.cpp direct_trigonometry/polygon.cpp direct_trigonometry/separator.cpp diff --git a/src/irregular/benders_decomposition.cpp b/src/irregular/benders_decomposition.cpp new file mode 100644 index 000000000..2b5a6bd7a --- /dev/null +++ b/src/irregular/benders_decomposition.cpp @@ -0,0 +1,917 @@ +#include "irregular/benders_decomposition.hpp" + +#include "packingsolver/irregular/algorithm_formatter.hpp" +#include "packingsolver/irregular/instance_builder.hpp" +#include "irregular/milp_nfp.hpp" + +#include "packingsolver/onedimensional/instance_builder.hpp" +#include "packingsolver/onedimensional/optimize.hpp" + +#include +#include +#include +#include +#include +#include + +using namespace packingsolver; +using namespace packingsolver::irregular; + +namespace +{ + +/** + * A no-good cut, turned into a onedimensional resource of a bin type. + * + * See 'rectangle::ResourceCut'. + */ +struct ResourceCut +{ + double capacity; + std::vector>> consumption; +}; + +/** + * Per-copy consumption schedule making the contribution of an item type to + * a resource equal to 'min(count, threshold)'. + * + * See 'rectangle::threshold_schedule'. + */ +std::vector threshold_schedule(ItemPos threshold) +{ + std::vector schedule(threshold, 1.0); + schedule.push_back(0.0); + return schedule; +} + +/** + * No-good cut forbidding a selection of items, and any selection containing + * it, in a bin. + */ +ResourceCut no_good_cut( + const std::vector>& selected_items) +{ + ResourceCut cut; + ItemPos number_of_items = 0; + for (const std::pair& p: selected_items) { + number_of_items += p.second; + cut.consumption.push_back({p.first, threshold_schedule(p.second)}); + } + cut.capacity = (double)number_of_items - 1; + return cut; +} + +/** Data of the subproblems kept between iterations. */ +struct SubproblemCache +{ + /** + * Outputs of the MILP NFP algorithm, for each bin type and selection of + * items, so that the same selection is never checked twice (the minimal + * infeasible subsets of different bins, and of different iterations, + * often share subsets). + */ + std::map< + std::pair>>, + MilpNfpOutput> outputs; + + /** Data of the MILP NFP algorithm (the pieces of the pairs of items). */ + MilpNfpCache milp_nfp_cache; +}; + +/** Result of checking whether a selection of items fits in a bin. */ +enum class SelectionFeasibility +{ + Feasible, + ProvenInfeasible, + Unknown, +}; + +/** + * Output of the MILP NFP algorithm for a selection of items, through the + * cache. + */ +MilpNfpOutput milp_nfp_output( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector>& selected_items, + const BendersDecompositionParameters& parameters, + SubproblemCache& subproblem_cache) +{ + auto key = std::make_pair(bin_type_id, selected_items); + auto it = subproblem_cache.outputs.find(key); + if (it != subproblem_cache.outputs.end()) + return it->second; + std::vector item_type_ids; + for (const std::pair& p: selected_items) + for (ItemPos copy = 0; copy < p.second; ++copy) + item_type_ids.push_back(p.first); + MilpNfpParameters milp_nfp_parameters; + milp_nfp_parameters.verbosity_level = 0; + milp_nfp_parameters.timer = parameters.timer; + if (parameters.optimization_mode == OptimizationMode::NotAnytimeSequential) + milp_nfp_parameters.number_of_threads = 1; + milp_nfp_parameters.cache = &subproblem_cache.milp_nfp_cache; + MilpNfpOutput output = milp_nfp( + instance, + bin_type_id, + item_type_ids, + milp_nfp_parameters); + // 'Unknown' may come from the timer, so it isn't stored. + if (output.status != MilpNfpStatus::Unknown) + subproblem_cache.outputs[key] = output; + return output; +} + +/** + * Check whether a selection of items fits in a bin of type 'bin_type_id'. + * + * If 'need_packing' is 'true', a selection is only 'Feasible' if a packing + * is found, and the packing is written in 'packing' (a solution of + * 'instance' with a single bin). Otherwise, a selection which the MILP NFP + * algorithm doesn't prove infeasible may also be considered 'Feasible', + * without a packing. + */ +SelectionFeasibility selection_feasibility( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector>& selected_items, + bool need_packing, + const BendersDecompositionParameters& parameters, + SubproblemCache& subproblem_cache, + Solution* packing = nullptr) +{ + if (selected_items.empty()) + return SelectionFeasibility::Feasible; + + if (parameters.subproblem_use_milp_nfp) { + MilpNfpOutput milp_nfp_output_ = milp_nfp_output( + instance, + bin_type_id, + selected_items, + parameters, + subproblem_cache); + if (milp_nfp_output_.status == MilpNfpStatus::Infeasible) + return SelectionFeasibility::ProvenInfeasible; + if (milp_nfp_output_.status == MilpNfpStatus::Feasible) { + if (!need_packing) + return SelectionFeasibility::Feasible; + // The solution of the relaxation may be a packing. + if (packing != nullptr + && milp_nfp_solution( + instance, + bin_type_id, + milp_nfp_output_, + *packing)) { + return SelectionFeasibility::Feasible; + } + } + } + + // Build the subproblem instance. + InstanceBuilder sub_instance_builder; + sub_instance_builder.set_objective(Objective::Feasibility); + sub_instance_builder.set_parameters(instance.parameters()); + BinTypeId sub_bin_type_id = sub_instance_builder.add_bin_type(instance, bin_type_id); + sub_instance_builder.set_bin_type_copies(sub_bin_type_id, 1); + sub_instance_builder.set_bin_type_copies_min(sub_bin_type_id, 0); + std::vector sub_to_orig; + for (const std::pair& p: selected_items) { + ItemTypeId sub_item_type_id = sub_instance_builder.add_item_type(instance, p.first); + sub_instance_builder.set_item_type_copies(sub_item_type_id, p.second); + sub_to_orig.push_back(p.first); + } + Instance sub_instance = sub_instance_builder.build(); + + // Solve it. + OptimizeParameters sub_parameters; + sub_parameters.verbosity_level = 0; + sub_parameters.timer = parameters.timer; + sub_parameters.optimization_mode + = (parameters.optimization_mode == OptimizationMode::NotAnytimeSequential)? + OptimizationMode::NotAnytimeSequential: + OptimizationMode::NotAnytimeDeterministic; + sub_parameters.not_anytime_tree_search_queue_size = parameters.subproblem_queue_size; + sub_parameters.linear_programming_solver_name = parameters.linear_programming_solver_name; + irregular::Output sub_output = optimize(sub_instance, sub_parameters); + const Solution& sub_solution = sub_output.solution_pool.best(); + + if (sub_solution.feasible()) { + if (packing != nullptr) { + *packing = Solution(instance); + packing->append_bin(sub_solution, 0, 1, {bin_type_id}, sub_to_orig); + } + return SelectionFeasibility::Feasible; + } + if (sub_output.is_proven_infeasible) + return SelectionFeasibility::ProvenInfeasible; + return SelectionFeasibility::Unknown; +} + +/** + * Aggregate a list of items (one entry per copy) into (item type, number of + * copies) pairs, skipping the removed ones. + */ +std::vector> aggregate_units( + const Instance& instance, + const std::vector& units, + const std::vector& removed) +{ + std::vector counts(instance.number_of_item_types(), 0); + for (std::size_t unit_pos = 0; unit_pos < units.size(); ++unit_pos) + if (!removed[unit_pos]) + counts[units[unit_pos]]++; + std::vector> result; + for (ItemTypeId item_type_id = 0; + item_type_id < instance.number_of_item_types(); + ++item_type_id) { + if (counts[item_type_id] > 0) + result.push_back({item_type_id, counts[item_type_id]}); + } + return result; +} + +/** + * Return 'true' iff 'selected_items' contains at least the copies of + * 'subset'. Both are sorted by item type. + */ +bool contains( + const std::vector>& selected_items, + const std::vector>& subset) +{ + auto it = selected_items.begin(); + for (const std::pair& p: subset) { + while (it != selected_items.end() && it->first < p.first) + ++it; + if (it == selected_items.end() + || it->first != p.first + || it->second < p.second) { + return false; + } + } + return true; +} + +/** + * Lift a no-good cut forbidding the proven infeasible items 'items' (S) in a + * bin of type 'bin_type_id': 'sum_{i in S} min(x_i, n_i) <= |S| - 1'. + * + * The item types not in S are considered one by one, largest first. An item + * type j gets the coefficient 1 if every selection made of a copy of j and + * of |S| - 1 items of S and of the item types already lifted (L) is proven + * infeasible: then no feasible selection reaches |S| on the lifted cut, so + * it stays valid. Since the cut is a no-good cut, it means that j can + * replace any item of S (and of L) in it. + * + * A selection containing items forbidden by a proven cut is infeasible + * without solving it. + */ +ResourceCut lift_no_good_cut( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector>& items, + const std::vector>>& proven_cut_items, + const BendersDecompositionParameters& parameters, + SubproblemCache& subproblem_cache, + BendersDecompositionOutput& output) +{ + ResourceCut cut = no_good_cut(items); + ItemPos cut_size = 0; + std::vector in_cut(instance.number_of_item_types(), false); + std::vector units; + for (const std::pair& p: items) { + cut_size += p.second; + in_cut[p.first] = true; + for (ItemPos copy = 0; copy < p.second; ++copy) + units.push_back(p.first); + } + + // Return 'true' iff a selection is proven infeasible. + auto proven_infeasible = [&](const std::vector>& selection) -> bool + { + for (const auto& cut_items: proven_cut_items) + if (contains(selection, cut_items)) + return true; + return milp_nfp_output( + instance, + bin_type_id, + selection, + parameters, + subproblem_cache).status == MilpNfpStatus::Infeasible; + }; + + std::vector candidates; + for (ItemTypeId item_type_id = 0; + item_type_id < instance.number_of_item_types(); + ++item_type_id) { + if (!in_cut[item_type_id]) + candidates.push_back(item_type_id); + } + std::stable_sort( + candidates.begin(), + candidates.end(), + [&instance](ItemTypeId item_type_id_1, ItemTypeId item_type_id_2) + { + return instance.item_type(item_type_id_1).area_scaled + > instance.item_type(item_type_id_2).area_scaled; + }); + + for (ItemTypeId candidate_id: candidates) { + if ((Counter)units.size() - cut_size + >= parameters.maximum_number_of_lifted_item_types) { + break; + } + if (parameters.timer.needs_to_end()) + break; + // Enumerate the selections of |S| - 1 items of S and L, by the + // items removed. + std::vector removed(units.size(), false); + std::size_t number_of_removed_units = units.size() - (cut_size - 1); + std::set>> checked; + bool valid = true; + std::function enumerate = [&]( + std::size_t unit_pos, + std::size_t number_of_removed) + { + if (!valid) + return; + if (number_of_removed == number_of_removed_units) { + std::vector selection_units = {candidate_id}; + for (std::size_t pos = 0; pos < units.size(); ++pos) + if (!removed[pos]) + selection_units.push_back(units[pos]); + std::vector none(selection_units.size(), false); + std::vector> selection + = aggregate_units(instance, selection_units, none); + if (!checked.insert(selection).second) + return; + if (!proven_infeasible(selection)) + valid = false; + return; + } + if (unit_pos == units.size()) + return; + removed[unit_pos] = true; + enumerate(unit_pos + 1, number_of_removed + 1); + removed[unit_pos] = false; + enumerate(unit_pos + 1, number_of_removed); + }; + enumerate(0, 0); + if (!valid || parameters.timer.needs_to_end()) + continue; + cut.consumption.push_back({candidate_id, threshold_schedule(1)}); + units.push_back(candidate_id); + output.number_of_lifted_coefficients++; + } + return cut; +} + +/** + * Search for an infeasible subset of a selection of items with the MILP NFP + * algorithm, by adding its items one by one, largest first. Return the first + * subset proven infeasible, or an empty one if none is. + * + * Proving that a large selection doesn't fit may be much more expensive than + * proving it for a few of its items, and a small infeasible subset is what + * the no-good cut needs anyway. The last subset checked is the whole + * selection, so it is not checked twice (see 'SubproblemCache'). + */ +std::vector> find_infeasible_prefix( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector>& selected_items, + const BendersDecompositionParameters& parameters, + SubproblemCache& subproblem_cache) +{ + std::vector units; + for (const std::pair& p: selected_items) + for (ItemPos copy = 0; copy < p.second; ++copy) + units.push_back(p.first); + std::stable_sort( + units.begin(), + units.end(), + [&instance](ItemTypeId item_type_id_1, ItemTypeId item_type_id_2) + { + return instance.item_type(item_type_id_1).area_scaled + > instance.item_type(item_type_id_2).area_scaled; + }); + + std::vector removed(units.size(), true); + for (std::size_t unit_pos = 0; unit_pos < units.size(); ++unit_pos) { + removed[unit_pos] = false; + std::vector> prefix + = aggregate_units(instance, units, removed); + MilpNfpStatus status = milp_nfp_output( + instance, + bin_type_id, + prefix, + parameters, + subproblem_cache).status; + if (status == MilpNfpStatus::Infeasible) + return prefix; + if (status == MilpNfpStatus::Unknown) + break; + } + return {}; +} + +/** + * A minimal infeasible subset, and whether every check of its derivation + * proved infeasibility (see 'rectangle::MinimalInfeasibleSubset'). + */ +struct MinimalInfeasibleSubset +{ + std::vector> items; + bool proven; +}; + +/** + * DFS step of 'enumerate_minimal_infeasible_subsets': try removing each + * unit from 'next_unit_pos' onwards, recurse on the selections which are not + * feasible, and record the current selection if none is. + */ +void enumerate_minimal_infeasible_subsets_dfs( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector& units, + std::vector& removed, + std::size_t remaining_count, + std::size_t next_unit_pos, + bool path_proven, + const BendersDecompositionParameters& parameters, + SubproblemCache& subproblem_cache, + std::vector& subsets) +{ + bool any_child_infeasible = false; + for (std::size_t unit_pos = next_unit_pos; + unit_pos < units.size() + && (Counter)subsets.size() < parameters.maximum_number_of_no_good_cuts_per_bin + && remaining_count > 1; + ++unit_pos) { + if (parameters.timer.needs_to_end()) + break; + removed[unit_pos] = true; + SelectionFeasibility child_feasibility = selection_feasibility( + instance, + bin_type_id, + aggregate_units(instance, units, removed), + false, + parameters, + subproblem_cache); + if (child_feasibility != SelectionFeasibility::Feasible) { + any_child_infeasible = true; + enumerate_minimal_infeasible_subsets_dfs( + instance, + bin_type_id, + units, + removed, + remaining_count - 1, + unit_pos + 1, + path_proven && (child_feasibility == SelectionFeasibility::ProvenInfeasible), + parameters, + subproblem_cache, + subsets); + } + removed[unit_pos] = false; + } + + if (!any_child_infeasible + && (Counter)subsets.size() < parameters.maximum_number_of_no_good_cuts_per_bin) { + subsets.push_back({aggregate_units(instance, units, removed), path_proven}); + } +} + +/** + * Enumerate minimal infeasible subsets of an infeasible selection of items. + * + * The items are sorted by increasing area, so that the small items are + * removed first. + */ +std::vector enumerate_minimal_infeasible_subsets( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector>& selected_items, + bool selection_proven_infeasible, + const BendersDecompositionParameters& parameters, + SubproblemCache& subproblem_cache) +{ + std::vector units; + for (const std::pair& p: selected_items) + for (ItemPos copy = 0; copy < p.second; ++copy) + units.push_back(p.first); + std::stable_sort( + units.begin(), + units.end(), + [&instance](ItemTypeId item_type_id_1, ItemTypeId item_type_id_2) + { + return instance.item_type(item_type_id_1).area_scaled + < instance.item_type(item_type_id_2).area_scaled; + }); + + std::vector removed(units.size(), false); + std::vector subsets; + enumerate_minimal_infeasible_subsets_dfs( + instance, + bin_type_id, + units, + removed, + units.size(), + 0, + selection_proven_infeasible, + parameters, + subproblem_cache, + subsets); + return subsets; +} + +/** Add a cut as a new resource of a bin type of the master problem. */ +void add_cut_as_resource( + onedimensional::InstanceBuilder& master_instance_builder, + BinTypeId master_bin_type_id, + const ResourceCut& cut) +{ + ResourceId resource_id = master_instance_builder.add_bin_type_resource( + master_bin_type_id, cut.capacity); + for (const std::pair>& entry: cut.consumption) { + master_instance_builder.add_resource_consumption( + master_bin_type_id, + resource_id, + entry.first, + entry.second); + } +} + +/** + * Build the master problem: item types and bin types have the same ids as + * in the original instance. + * + * The areas of the item types are rounded down and the areas of the bin + * types rounded up, so that the master problem remains a relaxation. + */ +onedimensional::Instance build_master_instance( + const Instance& instance, + const std::vector>& cuts_by_bin_type) +{ + onedimensional::InstanceBuilder master_instance_builder; + master_instance_builder.set_objective(instance.objective()); + + for (BinTypeId bin_type_id = 0; + bin_type_id < instance.number_of_bin_types(); + ++bin_type_id) { + const BinType& bin_type = instance.bin_type(bin_type_id); + BinTypeId master_bin_type_id = master_instance_builder.add_bin_type( + std::ceil(bin_type.area_scaled)); + master_instance_builder.set_bin_type_cost(master_bin_type_id, bin_type.cost); + master_instance_builder.set_bin_type_copies(master_bin_type_id, bin_type.copies); + master_instance_builder.set_bin_type_copies_min(master_bin_type_id, bin_type.copies_min); + + for (const ResourceCut& cut: cuts_by_bin_type[bin_type_id]) + add_cut_as_resource(master_instance_builder, master_bin_type_id, cut); + + // Resources of the instance. They are enforced by the master + // problem, so the subproblems don't need to consider them. + for (ResourceId resource_id = 0; + resource_id < bin_type.number_of_resources(); + ++resource_id) { + const Resource& resource = bin_type.resources[resource_id]; + ResourceId master_resource_id = master_instance_builder.add_bin_type_resource( + master_bin_type_id, + resource.capacity, + resource.penalize, + resource.penalty); + for (const std::pair>& entry: resource.item_consumptions) { + master_instance_builder.add_resource_consumption( + master_bin_type_id, + master_resource_id, + entry.first, + entry.second); + } + } + } + + 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); + ItemTypeId master_item_type_id = master_instance_builder.add_item_type( + std::floor(item_type.area_scaled)); + master_instance_builder.set_item_type_copies(master_item_type_id, item_type.copies); + master_instance_builder.set_item_type_copies_min(master_item_type_id, item_type.copies_min); + if (instance.objective() == Objective::Knapsack) + master_instance_builder.set_item_type_profit(master_item_type_id, item_type.profit); + } + + return master_instance_builder.build(); +} + +/** + * Aggregate the items of a bin of a onedimensional solution into (item type, + * number of copies) pairs. + */ +std::vector> aggregate_bin_items( + const onedimensional::SolutionBin& bin, + ItemTypeId number_of_item_types) +{ + std::vector counts(number_of_item_types, 0); + for (const onedimensional::SolutionItem& item: bin.items) + counts[item.item_type_id]++; + std::vector> result; + for (ItemTypeId item_type_id = 0; + item_type_id < number_of_item_types; + ++item_type_id) { + if (counts[item_type_id] > 0) + result.push_back({item_type_id, counts[item_type_id]}); + } + return result; +} + +/** + * Throw if a cut excludes a bin of 'solution'. + * + * Only called while every cut is proven: a feasible solution then satisfies + * all of them, so a violation means that a cut is wrong. + */ +void check_cuts_against_solution( + const Instance& instance, + const Solution& solution, + const std::vector>& cuts_by_bin_type) +{ + for (BinPos bin_pos = 0; + bin_pos < solution.number_of_different_bins(); + ++bin_pos) { + const SolutionBin& solution_bin = solution.bin(bin_pos); + std::vector item_type_counts(instance.number_of_item_types(), 0); + for (const SolutionItem& item: solution_bin.items) + item_type_counts[item.item_type_id]++; + for (const ResourceCut& cut: cuts_by_bin_type[solution_bin.bin_type_id]) { + double consumption = 0.0; + for (const std::pair>& entry: cut.consumption) { + ItemPos count = item_type_counts[entry.first]; + for (ItemPos copy = 0; copy < count; ++copy) { + consumption += (copy < (ItemPos)entry.second.size())? + entry.second[copy]: + entry.second.back(); + } + } + if (packingsolver::strictly_greater(consumption, cut.capacity)) { + throw std::logic_error( + FUNC_SIGNATURE + ": a no-good cut excludes " + "the current best solution."); + } + } + } +} + +double elapsed_time(std::chrono::steady_clock::time_point begin) +{ + return std::chrono::duration_cast>( + std::chrono::steady_clock::now() - begin).count(); +} + +} + +BendersDecompositionOutput packingsolver::irregular::benders_decomposition( + const Instance& instance, + const BendersDecompositionParameters& parameters) +{ + BendersDecompositionOutput output(instance); + AlgorithmFormatter algorithm_formatter(instance, parameters, output); + algorithm_formatter.start(); + algorithm_formatter.print_header(); + + if (instance.objective() != Objective::Knapsack + && instance.objective() != Objective::BinPacking + && instance.objective() != Objective::VariableSizedBinPacking) { + std::stringstream ss; + ss << FUNC_SIGNATURE << ": " + << "objective \"" + << instance.objective() << "\" not supported."; + throw std::invalid_argument(ss.str()); + } + + // No-good cuts, per bin type, and the items they forbid. + std::vector> cuts_by_bin_type(instance.number_of_bin_types()); + std::vector>>> cut_items_by_bin_type( + instance.number_of_bin_types()); + std::vector>>> proven_cut_items_by_bin_type( + instance.number_of_bin_types()); + + SubproblemCache subproblem_cache; + + // 'true' iff every cut added so far is proven. Otherwise, the bound of + // the master problem is not a bound of the instance. + bool all_cuts_proven = true; + + for (output.number_of_iterations = 0; + ; + ++output.number_of_iterations) { + + // Check the maximum number of iterations. + if (parameters.optimization_mode != OptimizationMode::Anytime + && parameters.optimization_mode != OptimizationMode::Exact + && parameters.not_anytime_maximum_number_of_iterations >= 0 + && output.number_of_iterations >= parameters.not_anytime_maximum_number_of_iterations) { + break; + } + + // Build and solve the master problem. + auto master_begin = std::chrono::steady_clock::now(); + onedimensional::Instance master_instance = build_master_instance( + instance, + cuts_by_bin_type); + onedimensional::OptimizeParameters master_parameters; + master_parameters.verbosity_level = 0; + master_parameters.timer = parameters.timer; + // In 'Exact' mode, the master problem is solved in 'Exact' mode so + // that its bound is actually proven. + master_parameters.optimization_mode + = (parameters.optimization_mode == OptimizationMode::Exact)? + OptimizationMode::Exact: + (parameters.optimization_mode == OptimizationMode::NotAnytimeSequential)? + OptimizationMode::NotAnytimeSequential: + OptimizationMode::NotAnytimeDeterministic; + master_parameters.use_milp_assignment = true; + master_parameters.linear_programming_solver_name = parameters.linear_programming_solver_name; + onedimensional::Output master_output = onedimensional::optimize( + master_instance, master_parameters); + output.master_time += elapsed_time(master_begin); + + // Check end. + if (parameters.timer.needs_to_end()) + break; + + // Update the bound. + if (all_cuts_proven) { + if (master_output.is_proven_infeasible) { + algorithm_formatter.update_is_proven_infeasible(); + } else if (instance.objective() == Objective::Knapsack) { + algorithm_formatter.update_knapsack_bound(master_output.knapsack_bound); + } else if (instance.objective() == Objective::BinPacking) { + algorithm_formatter.update_bin_packing_bound(master_output.bin_packing_bound); + } else if (instance.objective() == Objective::VariableSizedBinPacking) { + algorithm_formatter.update_variable_sized_bin_packing_bound( + master_output.variable_sized_bin_packing_bound); + } + } + if (master_output.is_proven_infeasible) + break; + + const onedimensional::Solution& master_solution = master_output.solution_pool.best(); + if (master_solution.number_of_bins() == 0 + && instance.number_of_items() > 0 + && instance.objective() != Objective::Knapsack) { + throw std::runtime_error( + FUNC_SIGNATURE + ": " + "the master problem should not be infeasible."); + } + + // Stop if the solution of the master problem can't improve the best + // solution. + if (output.solution_pool.best().feasible()) { + if (instance.objective() == Objective::Knapsack) { + if (master_solution.profit() <= output.solution_pool.best().profit()) + break; + } else if (instance.objective() == Objective::BinPacking) { + if (master_solution.number_of_bins() >= output.solution_pool.best().number_of_bins()) + break; + } else if (instance.objective() == Objective::VariableSizedBinPacking) { + if (master_solution.cost() >= output.solution_pool.best().cost()) + break; + } + } + + // Solve the subproblem of each bin of the solution of the master + // problem. + Solution solution(instance); + bool all_bins_feasible = true; + bool need_to_end = false; + for (BinPos master_bin_pos = 0; + master_bin_pos < master_solution.number_of_different_bins(); + ++master_bin_pos) { + const onedimensional::SolutionBin& master_bin = master_solution.bin(master_bin_pos); + std::vector> selected_items = aggregate_bin_items( + master_bin, instance.number_of_item_types()); + + auto subproblem_begin = std::chrono::steady_clock::now(); + Solution packing(instance); + SelectionFeasibility feasibility = SelectionFeasibility::Unknown; + // Infeasible subset of the selection, from which the cuts are + // derived. + std::vector> infeasible_items; + // The selection may contain items forbidden by a cut added + // earlier in this iteration, for another bin. + bool already_cut = false; + for (std::size_t cut_pos = 0; + cut_pos < cut_items_by_bin_type[master_bin.bin_type_id].size(); + ++cut_pos) { + if (contains(selected_items, cut_items_by_bin_type[master_bin.bin_type_id][cut_pos])) { + already_cut = true; + break; + } + } + if (already_cut) { + all_bins_feasible = false; + continue; + } + if (parameters.subproblem_use_milp_nfp) { + infeasible_items = find_infeasible_prefix( + instance, + master_bin.bin_type_id, + selected_items, + parameters, + subproblem_cache); + if (!infeasible_items.empty()) + feasibility = SelectionFeasibility::ProvenInfeasible; + } + if (infeasible_items.empty()) { + feasibility = selection_feasibility( + instance, + master_bin.bin_type_id, + selected_items, + true, + parameters, + subproblem_cache, + &packing); + infeasible_items = selected_items; + } + output.subproblem_time += elapsed_time(subproblem_begin); + + if (feasibility == SelectionFeasibility::Feasible) { + // The 'copies' identical bins of the master solution share + // the same packing. + solution.append_bin(packing, 0, master_bin.copies); + continue; + } + all_bins_feasible = false; + + // Check end. + if (parameters.timer.needs_to_end()) { + need_to_end = true; + break; + } + + // Add a no-good cut for each minimal infeasible subset of the + // infeasible items. A cut which isn't proven may still help the master + // problem converge, but then its bound isn't a bound anymore. + auto minimal_infeasible_subsets_begin = std::chrono::steady_clock::now(); + std::vector subsets = enumerate_minimal_infeasible_subsets( + instance, + master_bin.bin_type_id, + infeasible_items, + feasibility == SelectionFeasibility::ProvenInfeasible, + parameters, + subproblem_cache); + output.minimal_infeasible_subsets_time += elapsed_time(minimal_infeasible_subsets_begin); + for (const MinimalInfeasibleSubset& subset: subsets) { + if (parameters.subproblem_use_milp_nfp + && subset.proven + && parameters.maximum_number_of_lifted_item_types > 0) { + auto lifting_begin = std::chrono::steady_clock::now(); + cuts_by_bin_type[master_bin.bin_type_id].push_back(lift_no_good_cut( + instance, + master_bin.bin_type_id, + subset.items, + proven_cut_items_by_bin_type[master_bin.bin_type_id], + parameters, + subproblem_cache, + output)); + output.lifting_time += elapsed_time(lifting_begin); + } else { + cuts_by_bin_type[master_bin.bin_type_id].push_back(no_good_cut(subset.items)); + } + cut_items_by_bin_type[master_bin.bin_type_id].push_back(subset.items); + if (subset.proven) + proven_cut_items_by_bin_type[master_bin.bin_type_id].push_back(subset.items); + output.number_of_no_good_cuts++; + if (!subset.proven) { + output.number_of_unproven_no_good_cuts++; + all_cuts_proven = false; + } + } + } + + // Update the solution. + if (solution.number_of_bins() > 0) { + std::stringstream ss; + ss << "BD it " << output.number_of_iterations; + algorithm_formatter.update_solution(solution, ss.str()); + } + + if (all_cuts_proven) { + check_cuts_against_solution( + instance, + output.solution_pool.best(), + cuts_by_bin_type); + } + + if (need_to_end) + break; + + // Every bin of the solution of the master problem is packed: it is + // optimal given the cuts. + if (all_bins_feasible) + break; + } + + algorithm_formatter.end(); + return output; +} diff --git a/src/irregular/benders_decomposition.hpp b/src/irregular/benders_decomposition.hpp new file mode 100644 index 000000000..3fee36754 --- /dev/null +++ b/src/irregular/benders_decomposition.hpp @@ -0,0 +1,146 @@ +/** + * Benders decomposition + * + * Logic-based Benders decomposition, as the rectangle one (see + * 'rectangle/benders_decomposition.hpp'), with a onedimensional master + * problem: + * - The master problem assigns the items to bins, each item having its area + * as length and each bin its area as capacity. Its bound is a bound of the + * instance as long as every cut added is valid. + * - For each bin of the solution of the master problem, a subproblem checks + * whether its items fit in it. If they don't, a no-good cut forbids the + * minimal infeasible subsets of them in a bin of this type. + * The algorithm stops when every bin of the solution of the master problem + * is packed: this solution is then optimal. + * + * The subproblem is solved with the 'Feasibility' objective of 'optimize'. + * It finds packings, but rarely proves that items don't fit, so the cuts are + * then mostly not proven, and the bound of the master problem is not + * reported. With 'subproblem_use_milp_nfp', the MILP NFP algorithm (see + * 'milp_nfp.hpp') is first used to prove that the items don't fit; the cuts + * it generates are proven. + * + * Supported objectives: 'Knapsack', 'BinPacking', 'VariableSizedBinPacking'. + */ + +#pragma once + +#include "packingsolver/irregular/optimize.hpp" + +namespace packingsolver +{ +namespace irregular +{ + +struct BendersDecompositionOutput: Output +{ + /** Constructor. */ + BendersDecompositionOutput(const Instance& instance): + Output(instance) { } + + /** Number of iterations. */ + Counter number_of_iterations = 0; + + /** Number of no-good cuts. */ + Counter number_of_no_good_cuts = 0; + + /** Number of no-good cuts which are not proven. */ + Counter number_of_unproven_no_good_cuts = 0; + + /** Total time spent building and solving the master problem. */ + double master_time = 0.0; + + /** Total time spent solving the subproblems. */ + double subproblem_time = 0.0; + + /** Total time spent enumerating minimal infeasible subsets. */ + double minimal_infeasible_subsets_time = 0.0; + + /** Number of item types lifted in the no-good cuts. */ + Counter number_of_lifted_coefficients = 0; + + /** Total time spent lifting the no-good cuts. */ + double lifting_time = 0.0; + + virtual nlohmann::json to_json() const override + { + nlohmann::json json = Output::to_json(); + json["NumberOfIterations"] = number_of_iterations; + json["NumberOfNoGoodCuts"] = number_of_no_good_cuts; + json["NumberOfUnprovenNoGoodCuts"] = number_of_unproven_no_good_cuts; + json["MasterTime"] = master_time; + json["SubproblemTime"] = subproblem_time; + json["MinimalInfeasibleSubsetsTime"] = minimal_infeasible_subsets_time; + json["NumberOfLiftedCoefficients"] = number_of_lifted_coefficients; + json["LiftingTime"] = lifting_time; + return json; + } + + virtual int format_width() const override + { + return 40; + } + + virtual void format(std::ostream& os) const override + { + Output::format(os); + int width = format_width(); + os + << std::setw(width) << std::left << "Number of iterations: " << number_of_iterations << std::endl + << std::setw(width) << std::left << "Number of no-good cuts: " << number_of_no_good_cuts << std::endl + << std::setw(width) << std::left << "Number of unproven no-good cuts: " << number_of_unproven_no_good_cuts << std::endl + << std::setw(width) << std::left << "Master time (s): " << master_time << std::endl + << std::setw(width) << std::left << "Subproblem time (s): " << subproblem_time << std::endl + << std::setw(width) << std::left << "Minimal infeasible subsets time (s): " << minimal_infeasible_subsets_time << std::endl + << std::setw(width) << std::left << "Number of lifted coefficients: " << number_of_lifted_coefficients << std::endl + << std::setw(width) << std::left << "Lifting time (s): " << lifting_time << std::endl + ; + } +}; + +struct BendersDecompositionParameters: packingsolver::Parameters +{ + /** Linear programming solver of the master problem and subproblems. */ + columngenerationsolver::SolverName linear_programming_solver_name + = columngenerationsolver::SolverName::CLP; + + /** Optimization mode. */ + OptimizationMode optimization_mode = OptimizationMode::Anytime; + + /** + * Maximum number of iterations, in non-'Anytime' optimization modes only + * (-1: unlimited). + */ + Counter not_anytime_maximum_number_of_iterations = -1; + + /** Size of the queue of the tree search of the subproblems. */ + NodeId subproblem_queue_size = 512; + + /** + * Use the MILP NFP algorithm to prove that the items of a bin don't fit. + */ + bool subproblem_use_milp_nfp = false; + + /** + * Maximum number of minimal infeasible subsets, and thus of no-good cuts, + * per infeasible bin. + * + * Each subset costs many subproblem solves, which are expensive for + * irregular items, so a single one is searched by default. + */ + Counter maximum_number_of_no_good_cuts_per_bin = 1; + + /** + * Maximum number of item types lifted in a no-good cut (see + * 'lift_no_good_cut' in 'benders_decomposition.cpp'). Only with the MILP + * NFP algorithm, which proves that the selections don't fit. + */ + Counter maximum_number_of_lifted_item_types = 4; +}; + +BendersDecompositionOutput benders_decomposition( + const Instance& instance, + const BendersDecompositionParameters& parameters); + +} +} diff --git a/src/irregular/main.cpp b/src/irregular/main.cpp index 13cd00eba..7fdd8ceec 100644 --- a/src/irregular/main.cpp +++ b/src/irregular/main.cpp @@ -95,6 +95,9 @@ int main(int argc, char *argv[]) ("use-sequential-single-knapsack,", po::value(), "enable sequential-single-knapsack") ("use-sequential-value-correction,", po::value(), "enable sequential-value-correction") ("use-column-generation,", po::value(), "enable column-generation") + ("use-benders-decomposition,", po::value(), "enable Benders decomposition algorithm") + ("benders-decomposition-use-milp-nfp,", po::value(), "use the MILP NFP algorithm in the subproblems of the Benders decomposition algorithm") + ("use-milp-nfp,", po::value(), "use the MILP NFP algorithm (Feasibility objective with a single bin)") ("use-dichotomic-search,", po::value(), "enable dichotomic search") ("reduce,", po::value(), "enable/disable instance reduction (preprocessing)") ("initial-maximum-approximation-ratio,", po::value(), "initial maximum approximation ratio") @@ -200,6 +203,12 @@ int main(int argc, char *argv[]) parameters.use_sequential_value_correction = vm["use-sequential-value-correction"].as(); if (vm.count("use-column-generation")) parameters.use_column_generation = vm["use-column-generation"].as(); + if (vm.count("use-benders-decomposition")) + parameters.use_benders_decomposition = vm["use-benders-decomposition"].as(); + if (vm.count("benders-decomposition-use-milp-nfp")) + parameters.benders_decomposition_use_milp_nfp = vm["benders-decomposition-use-milp-nfp"].as(); + if (vm.count("use-milp-nfp")) + parameters.use_milp_nfp = vm["use-milp-nfp"].as(); if (vm.count("use-dichotomic-search")) parameters.use_dichotomic_search = vm["use-dichotomic-search"].as(); if (vm.count("reduce")) diff --git a/src/irregular/milp_nfp.cpp b/src/irregular/milp_nfp.cpp new file mode 100644 index 000000000..cbdd6e4f4 --- /dev/null +++ b/src/irregular/milp_nfp.cpp @@ -0,0 +1,999 @@ +#include "irregular/milp_nfp.hpp" + +#include "irregular/solution_builder.hpp" + +#include "shape/no_fit_polygon.hpp" +#include "shape/boolean_operations.hpp" +#include "shape/approximation.hpp" +#include "shape/convex_partition.hpp" + +#ifdef HIGHS_FOUND +#include "mathoptsolverscmake/mathopt_highs.hpp" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace packingsolver; +using namespace packingsolver::irregular; + +namespace +{ + +/** Item type in one of its rotations. */ +struct ItemTypeRotationData +{ + /** Shapes of the item, whose reference point is the origin. */ + std::vector shapes; + + /** Angle and mirroring of the rotation. */ + Angle angle; + bool mirror; + + /** Bounding box of the item. */ + AxisAlignedBoundingBox aabb; + + /** Area of the item. */ + AreaDbl area = 0; + + /** + * Inner-fit rectangle: positions of the reference point for which the + * bounding box of the item is in the bounding box of the bin. + */ + LengthDbl x_min; + LengthDbl x_max; + LengthDbl y_min; + LengthDbl y_max; +}; + +/** Constraint 'nx * dx + ny * dy >= c' on a relative position d. */ +struct HalfPlane +{ + LengthDbl nx; + LengthDbl ny; + LengthDbl c; +}; + +/** Convex piece of the feasible relative positions of a pair of items. */ +struct Piece +{ + /** Half-planes of the edges. */ + std::vector half_planes; + + /** Bounding box of the relative positions of the piece. */ + LengthDbl x_min = std::numeric_limits::infinity(); + LengthDbl x_max = -std::numeric_limits::infinity(); + LengthDbl y_min = std::numeric_limits::infinity(); + LengthDbl y_max = -std::numeric_limits::infinity(); +}; + +/** Bin type, and item type and rotation of each item of a pair. */ +using MilpNfpPairKey = std::tuple; + +/** + * Bin type, and sorted item types and rotations of the items of a rotation + * combination. + */ +using MilpNfpCombinationKey = std::pair>>; + +struct PairData +{ + /** Bounds of the relative position d = p_2 - p_1: R = IFP_2 - IFP_1. */ + LengthDbl x_min; + LengthDbl x_max; + LengthDbl y_min; + LengthDbl y_max; + + /** 'false' iff the two items can't overlap, whatever their positions. */ + bool interact = true; + + /** + * Convex pieces of the complement of int(NFP) intersecting R, including + * the feasible line segments and points of null area inside the NFP. + */ + std::vector pieces; +}; + +/** + * Return 'true' iff two lists of shapes are equal up to a translation (the + * one moving the minimum of their bounding boxes to the origin). + */ +bool equal_up_to_translation( + const std::vector& shapes_1, + const AxisAlignedBoundingBox& aabb_1, + const std::vector& shapes_2, + const AxisAlignedBoundingBox& aabb_2) +{ + if (shapes_1.size() != shapes_2.size()) + return false; + for (std::size_t shape_pos = 0; shape_pos < shapes_1.size(); ++shape_pos) { + ShapeWithHoles shape_1 = shapes_1[shape_pos]; + shape_1.shift(-aabb_1.x_min, -aabb_1.y_min); + ShapeWithHoles shape_2 = shapes_2[shape_pos]; + shape_2.shift(-aabb_2.x_min, -aabb_2.y_min); + if (!shape::equal(shape_1, shape_2)) + return false; + } + return true; +} + +/** + * Add the half-planes of the edges of a convex polygon, anticlockwise, to a + * piece. + */ +void add_convex_polygon( + const std::vector& vertices, + Piece& piece) +{ + for (std::size_t vertex_pos = 0; vertex_pos < vertices.size(); ++vertex_pos) { + const Point& start = vertices[vertex_pos]; + const Point& end = vertices[(vertex_pos + 1) % vertices.size()]; + piece.x_min = (std::min)(piece.x_min, start.x); + piece.x_max = (std::max)(piece.x_max, start.x); + piece.y_min = (std::min)(piece.y_min, start.y); + piece.y_max = (std::max)(piece.y_max, start.y); + LengthDbl ex = end.x - start.x; + LengthDbl ey = end.y - start.y; + LengthDbl norm = std::sqrt(ex * ex + ey * ey); + if (norm == 0.0) + continue; + // The interior is on the left of the edge. + HalfPlane half_plane; + half_plane.nx = -ey / norm; + half_plane.ny = ex / norm; + half_plane.c = half_plane.nx * start.x + half_plane.ny * start.y; + piece.half_planes.push_back(half_plane); + } +} + +/** Piece made of a line segment: both sides of its line, and its ends. */ +Piece segment_piece( + const Point& start, + const Point& end) +{ + Piece piece; + add_convex_polygon({start, end}, piece); + LengthDbl ex = end.x - start.x; + LengthDbl ey = end.y - start.y; + LengthDbl norm = std::sqrt(ex * ex + ey * ey); + if (norm > 0.0) { + piece.half_planes.push_back({ex / norm, ey / norm, (ex * start.x + ey * start.y) / norm}); + piece.half_planes.push_back({-ex / norm, -ey / norm, -(ex * end.x + ey * end.y) / norm}); + } + return piece; +} + +/** Piece made of an axis-aligned rectangle. */ +Piece rectangle_piece(const AxisAlignedBoundingBox& aabb) +{ + // The rectangle may be degenerate, so its half-planes are added directly. + Piece piece; + piece.half_planes = { + {1, 0, aabb.x_min}, + {-1, 0, -aabb.x_max}, + {0, 1, aabb.y_min}, + {0, -1, -aabb.y_max}}; + piece.x_min = aabb.x_min; + piece.x_max = aabb.x_max; + piece.y_min = aabb.y_min; + piece.y_max = aabb.y_max; + return piece; +} + +PairData compute_pair_data( + const ItemTypeRotationData& item_1, + const ItemTypeRotationData& item_2) +{ + PairData pair_data; + pair_data.x_min = item_2.x_min - item_1.x_max; + pair_data.x_max = item_2.x_max - item_1.x_min; + pair_data.y_min = item_2.y_min - item_1.y_max; + pair_data.y_max = item_2.y_max - item_1.y_min; + + // No-fit polygon of the two items: union of the no-fit polygons of their + // shapes, with the feasible elements and points of null area strictly + // inside them. + std::vector nfps; + std::vector null_area_pieces; + AxisAlignedBoundingBox nfp_aabb; + for (const ShapeWithHoles& shape_1: item_1.shapes) { + for (const ShapeWithHoles& shape_2: item_2.shapes) { + shape::NoFitPolygonOutput nfp = shape::no_fit_polygon(shape_1, shape_2); + for (const ShapeWithHoles& part: nfp.nfp.shapes_with_holes) { + nfp_aabb = merge(nfp_aabb, part.compute_min_max()); + nfps.push_back(part); + } + // With several shapes, an element or a point may be inside the + // no-fit polygon of other shapes; keeping it only weakens the + // relaxation. + for (const ShapeElement& element: nfp.feasible_elements) { + // An arc is relaxed by its bounding box. + null_area_pieces.push_back((element.type == shape::ShapeElementType::LineSegment)? + segment_piece(element.start, element.end): + rectangle_piece(element.min_max())); + } + for (const Point& point: nfp.feasible_points) + null_area_pieces.push_back(rectangle_piece({point.x, point.x, point.y, point.y})); + } + } + if (nfps.empty() + || nfp_aabb.x_min >= pair_data.x_max + || nfp_aabb.x_max <= pair_data.x_min + || nfp_aabb.y_min >= pair_data.y_max + || nfp_aabb.y_max <= pair_data.y_min) { + pair_data.interact = false; + return pair_data; + } + + // Feasible relative positions. Since the bounds of the positions already + // keep d in R, the rectangle may be larger than R; it is, so that it + // doesn't vanish if R is degenerate. + LengthDbl enlargement = (pair_data.x_max - pair_data.x_min) + + (pair_data.y_max - pair_data.y_min) + 1; + shape::MultiShapeWithHoles region; + region.shapes_with_holes.push_back({shape::build_rectangle( + pair_data.x_min - enlargement, + pair_data.x_max + enlargement, + pair_data.y_min - enlargement, + pair_data.y_max + enlargement)}); + shape::MultiShapeWithHoles feasible_region = shape::compute_difference( + region, + shape::compute_union(nfps)); + + std::vector pieces = null_area_pieces; + for (const ShapeWithHoles& part: feasible_region.shapes_with_holes) { + // The approximation of the arcs contains the region. + ShapeWithHoles polygon = (part.is_polygon())? + part: + shape::approximate_by_line_segments(part, 1e-2 * enlargement); + for (const Shape& convex_part: shape::compute_convex_partition(polygon)) { + // The parts are anticlockwise. + std::vector vertices; + for (const shape::ShapeElement& element: convex_part.elements) + vertices.push_back(element.start); + Piece piece; + add_convex_polygon(vertices, piece); + pieces.push_back(piece); + } + } + + // Keep the pieces intersecting R. + for (const Piece& piece: pieces) { + if (piece.x_min > pair_data.x_max + || piece.x_max < pair_data.x_min + || piece.y_min > pair_data.y_max + || piece.y_max < pair_data.y_min) { + continue; + } + pair_data.pieces.push_back(piece); + } + return pair_data; +} + +} + +struct packingsolver::irregular::MilpNfpCache::Data +{ + std::map pairs_data; + + /** Proven statuses of rotation combinations. */ + std::map combinations_statuses; + + /** Mutex of 'combinations_statuses', which the threads update. */ + std::mutex combinations_statuses_mutex; +}; + +packingsolver::irregular::MilpNfpCache::MilpNfpCache(): + data_(new Data()) { } + +packingsolver::irregular::MilpNfpCache::~MilpNfpCache() { } + +MilpNfpOutput packingsolver::irregular::milp_nfp( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector& item_type_ids, + const MilpNfpParameters& parameters) +{ + MilpNfpOutput output; + const BinType& bin_type = instance.bin_type(bin_type_id); + const AxisAlignedBoundingBox& bin_aabb = bin_type.aabb_scaled; + LengthDbl bin_spacing = instance.bin_spacing_scaled(bin_type_id); + LengthDbl bin_width = bin_aabb.x_max - bin_aabb.x_min - 2 * bin_spacing; + LengthDbl bin_height = bin_aabb.y_max - bin_aabb.y_min - 2 * bin_spacing; + + // Copies of the same item type are consecutive, for the symmetry + // breaking. + std::vector sorted_item_type_ids = item_type_ids; + std::sort(sorted_item_type_ids.begin(), sorted_item_type_ids.end()); + ItemPos number_of_items = sorted_item_type_ids.size(); + + // Rotations of the item types, whose inner-fit rectangle isn't empty. + std::map> rotations; + for (ItemTypeId item_type_id: sorted_item_type_ids) { + if (rotations.find(item_type_id) != rotations.end()) + continue; + const ItemType& item_type = instance.item_type(item_type_id); + if (!item_type.has_only_discrete_rotations()) { + output.status = MilpNfpStatus::Unknown; + return output; + } + std::vector& item_type_rotations = rotations[item_type_id]; + for (const AllowedRotation& allowed_rotation: item_type.allowed_rotations) { + ItemTypeRotationData rotation; + rotation.angle = allowed_rotation.start_angle; + rotation.mirror = allowed_rotation.mirror; + AxisAlignedBoundingBox aabb; + for (ItemShapePos item_shape_pos = 0; + item_shape_pos < (ItemShapePos)item_type.shapes.size(); + ++item_shape_pos) { + rotation.shapes.push_back(instance.item_shape_scaled( + item_type_id, + item_shape_pos, + allowed_rotation.start_angle, + allowed_rotation.mirror)); + aabb = merge(aabb, rotation.shapes.back().compute_min_max()); + rotation.area += rotation.shapes.back().compute_area(); + } + rotation.aabb = aabb; + rotation.x_min = bin_aabb.x_min + bin_spacing - aabb.x_min; + rotation.x_max = bin_aabb.x_max - bin_spacing - aabb.x_max; + rotation.y_min = bin_aabb.y_min + bin_spacing - aabb.y_min; + rotation.y_max = bin_aabb.y_max - bin_spacing - aabb.y_max; + // An item which fits exactly may get a slightly empty inner-fit + // rectangle because of rounding errors. + if (strictly_lesser(rotation.x_max, rotation.x_min) + || strictly_lesser(rotation.y_max, rotation.y_min)) { + continue; + } + rotation.x_max = (std::max)(rotation.x_max, rotation.x_min); + rotation.y_max = (std::max)(rotation.y_max, rotation.y_min); + // Two rotations giving the same shape (for example, the + // rotations by 0 and 180 degrees of a rectangle) are the same. + bool duplicate = false; + for (const ItemTypeRotationData& other_rotation: item_type_rotations) { + if (equal_up_to_translation( + rotation.shapes, rotation.aabb, + other_rotation.shapes, other_rotation.aabb)) { + duplicate = true; + break; + } + } + if (duplicate) + continue; + item_type_rotations.push_back(rotation); + } + if (item_type_rotations.empty()) { + output.status = MilpNfpStatus::Infeasible; + return output; + } + } + if (number_of_items <= 1) { + output.status = MilpNfpStatus::Feasible; + return output; + } + + // Symmetry of the bin: the relaxation only considers the bounding box of + // the bin, so rotating a solution by 180 degrees gives another solution, + // in which the rotation of each item is turned by 180 degrees. If every + // rotation has such a counterpart, then one of the items may be + // restricted to one rotation of each pair. + // 'symmetric_rotation_ids[r]' is the rotation of the item type of + // 'symmetry_item_pos' turned by 180 degrees. + ItemPos symmetry_item_pos = -1; + std::vector symmetric_rotation_ids; + { + bool symmetric = true; + std::map> symmetric_rotations; + for (auto& entry: rotations) { + ItemTypeId item_type_id = entry.first; + const std::vector& item_type_rotations = entry.second; + std::vector& item_type_symmetric_rotations = symmetric_rotations[item_type_id]; + for (const ItemTypeRotationData& rotation: item_type_rotations) { + std::vector turned_shapes; + AxisAlignedBoundingBox turned_aabb; + for (ItemShapePos item_shape_pos = 0; + item_shape_pos < (ItemShapePos)rotation.shapes.size(); + ++item_shape_pos) { + turned_shapes.push_back(instance.item_shape_scaled( + item_type_id, + item_shape_pos, + rotation.angle + 180, + rotation.mirror)); + turned_aabb = merge(turned_aabb, turned_shapes.back().compute_min_max()); + } + Counter symmetric_rotation_id = -1; + for (Counter rotation_id = 0; + rotation_id < (Counter)item_type_rotations.size(); + ++rotation_id) { + if (equal_up_to_translation( + turned_shapes, turned_aabb, + item_type_rotations[rotation_id].shapes, + item_type_rotations[rotation_id].aabb)) { + symmetric_rotation_id = rotation_id; + break; + } + } + if (symmetric_rotation_id == -1) { + symmetric = false; + break; + } + item_type_symmetric_rotations.push_back(symmetric_rotation_id); + } + if (!symmetric) + break; + } + // The restricted item must be the only copy of its item type, so + // that the symmetry breaking between identical items still holds. + if (symmetric) { + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + ItemTypeId item_type_id = sorted_item_type_ids[item_pos]; + if ((item_pos > 0 && sorted_item_type_ids[item_pos - 1] == item_type_id) + || (item_pos + 1 < number_of_items && sorted_item_type_ids[item_pos + 1] == item_type_id)) { + continue; + } + const std::vector& item_type_symmetric_rotations = symmetric_rotations[item_type_id]; + bool useful = false; + for (Counter rotation_id = 0; + rotation_id < (Counter)item_type_symmetric_rotations.size(); + ++rotation_id) { + if (item_type_symmetric_rotations[rotation_id] != rotation_id) + useful = true; + } + if (useful) { + symmetry_item_pos = item_pos; + symmetric_rotation_ids = item_type_symmetric_rotations; + break; + } + } + } + } + + // Data of the pairs of item types in each of their rotations, computed + // when first needed, and kept in the cache if one is given. + MilpNfpCache local_cache; + MilpNfpCache::Data& cache_data = (parameters.cache != nullptr)? + *parameters.cache->data_: + *local_cache.data_; + std::map& pairs_data = cache_data.pairs_data; + auto pair_data = [&]( + ItemPos item_pos_1, + ItemPos item_pos_2, + Counter rotation_id_1, + Counter rotation_id_2) -> const PairData& + { + ItemTypeId item_type_id_1 = sorted_item_type_ids[item_pos_1]; + ItemTypeId item_type_id_2 = sorted_item_type_ids[item_pos_2]; + MilpNfpPairKey key = std::make_tuple( + bin_type_id, + item_type_id_1, + rotation_id_1, + item_type_id_2, + rotation_id_2); + auto it = pairs_data.find(key); + if (it == pairs_data.end()) { + it = pairs_data.insert({key, compute_pair_data( + rotations[item_type_id_1][rotation_id_1], + rotations[item_type_id_2][rotation_id_2])}).first; + } + return it->second; + }; + + // Rotation combinations; the rotations of identical items are + // non-decreasing. A partial combination in which a pair of items doesn't + // fit isn't extended. All the pair data needed later are computed here, + // so that they are only read by the threads. + std::vector> combinations; + { + std::vector rotation_ids(number_of_items, 0); + std::function enumerate = [&](ItemPos item_pos) + { + if (item_pos == number_of_items) { + combinations.push_back(rotation_ids); + return; + } + if (parameters.timer.needs_to_end()) + return; + ItemTypeId item_type_id = sorted_item_type_ids[item_pos]; + Counter rotation_id_start = (item_pos > 0 && sorted_item_type_ids[item_pos - 1] == item_type_id)? + rotation_ids[item_pos - 1]: 0; + for (Counter rotation_id = rotation_id_start; + rotation_id < (Counter)rotations[item_type_id].size(); + ++rotation_id) { + if (item_pos == symmetry_item_pos + && symmetric_rotation_ids[rotation_id] < rotation_id) { + continue; + } + bool fits = true; + for (ItemPos item_pos_1 = 0; item_pos_1 < item_pos; ++item_pos_1) { + const PairData& pair = pair_data( + item_pos_1, + item_pos, + rotation_ids[item_pos_1], + rotation_id); + if (pair.interact && pair.pieces.empty()) { + fits = false; + break; + } + } + if (!fits) + continue; + rotation_ids[item_pos] = rotation_id; + enumerate(item_pos + 1); + } + }; + enumerate(0); + } + if (parameters.timer.needs_to_end()) { + output.status = MilpNfpStatus::Unknown; + return output; + } + + // Return 'true' if a rotation combination is proven infeasible without a + // MILP, by the core widening. + auto prune = [&](const std::vector& rotation_ids) -> bool + { + // Core widening. + // + // The core of an item is the part of its y-range which no other item + // can reach, whatever their positions. Since the rotations are fixed, + // the horizontal band of the core of an item, across the bin, doesn't + // contain any other item. Thus the item can be widened to the width + // of the bin on its core. The cores of different items are disjoint, + // so the set of items doesn't fit if the sum of the widened areas + // exceeds the area of the bin. + AreaDbl widened_area = 0; + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + const ItemTypeRotationData& rotation = rotations[sorted_item_type_ids[item_pos]][rotation_ids[item_pos]]; + const AxisAlignedBoundingBox& aabb = rotation.aabb; + + // Parts of the y-range of the item, relative to its reference + // point, which another item can reach. + std::vector> intrusions; + for (ItemPos item_pos_2 = 0; item_pos_2 < number_of_items; ++item_pos_2) { + if (item_pos_2 == item_pos) + continue; + const AxisAlignedBoundingBox& aabb_2 = rotations[sorted_item_type_ids[item_pos_2]][rotation_ids[item_pos_2]].aabb; + // The pair data are for d = p_{pos_2} - p_{pos_1} with + // pos_1 < pos_2; the relative position of the other item is + // the opposite if it comes first. + bool reversed = (item_pos_2 < item_pos); + const PairData& pair = (reversed)? + pair_data(item_pos_2, item_pos, rotation_ids[item_pos_2], rotation_ids[item_pos]): + pair_data(item_pos, item_pos_2, rotation_ids[item_pos], rotation_ids[item_pos_2]); + auto add_intrusion = [&](LengthDbl dy_min, LengthDbl dy_max) + { + if (reversed) { + LengthDbl tmp = dy_min; + dy_min = -dy_max; + dy_max = -tmp; + } + LengthDbl y_min = (std::max)(dy_min + aabb_2.y_min, aabb.y_min); + LengthDbl y_max = (std::min)(dy_max + aabb_2.y_max, aabb.y_max); + if (y_min < y_max) + intrusions.push_back({y_min, y_max}); + }; + if (!pair.interact) { + add_intrusion(pair.y_min, pair.y_max); + } else { + // A piece is convex, so it contains a relative position + // for each y-coordinate of its range. + for (const Piece& piece: pair.pieces) + add_intrusion(piece.y_min, piece.y_max); + } + } + + // Core: complement of the union of the intrusions. + std::sort(intrusions.begin(), intrusions.end()); + std::vector> core; + LengthDbl y_current = aabb.y_min; + for (const auto& intrusion: intrusions) { + if (intrusion.first > y_current) + core.push_back({y_current, intrusion.first}); + y_current = (std::max)(y_current, intrusion.second); + } + if (aabb.y_max > y_current) + core.push_back({y_current, aabb.y_max}); + + // Widened area: the core across the bin, plus the area of the + // item outside of its core. + widened_area += rotation.area; + LengthDbl item_width = aabb.x_max - aabb.x_min; + for (const auto& strip: core) { + ShapeWithHoles strip_shape = {shape::build_rectangle( + aabb.x_min - item_width, + aabb.x_max + item_width, + strip.first, + strip.second)}; + widened_area += bin_width * (strip.second - strip.first); + for (const ShapeWithHoles& shape: rotation.shapes) + for (const ShapeWithHoles& part: shape::compute_intersection({shape, strip_shape}).shapes_with_holes) + widened_area -= part.compute_area(); + } + } + return strictly_greater_profit(widened_area, bin_width * bin_height); + }; + + // Add the constraints 'n . (p_2 - p_1) >= c - M * (1 - z)' of the pieces + // of a pair, where M is such that the constraint holds for every relative + // position d of 'relative_box' (x_min, x_max, y_min, y_max). + auto add_piece_constraints = []( + mathoptsolverscmake::MathOptModel& model, + ItemPos item_pos_1, + ItemPos item_pos_2, + const Piece& piece, + int piece_variable_id, + const std::array& relative_box) + { + for (const HalfPlane& half_plane: piece.half_planes) { + LengthDbl c = half_plane.c; + LengthDbl minimum = half_plane.nx * ((half_plane.nx > 0)? relative_box[0]: relative_box[1]) + + half_plane.ny * ((half_plane.ny > 0)? relative_box[2]: relative_box[3]); + LengthDbl big_m = c - minimum; + if (big_m <= 0) + continue; + model.constraints_starts.push_back(model.elements_variables.size()); + model.constraints_lower_bounds.push_back(c - big_m); + model.constraints_upper_bounds.push_back(std::numeric_limits::infinity()); + model.elements_variables.push_back(2 * item_pos_2); + model.elements_coefficients.push_back(half_plane.nx); + model.elements_variables.push_back(2 * item_pos_2 + 1); + model.elements_coefficients.push_back(half_plane.ny); + model.elements_variables.push_back(2 * item_pos_1); + model.elements_coefficients.push_back(-half_plane.nx); + model.elements_variables.push_back(2 * item_pos_1 + 1); + model.elements_coefficients.push_back(-half_plane.ny); + model.elements_variables.push_back(piece_variable_id); + model.elements_coefficients.push_back(-big_m); + } + }; + auto add_variable = []( + mathoptsolverscmake::MathOptModel& model, + double lower_bound, + double upper_bound, + mathoptsolverscmake::VariableType type) -> int + { + model.variables_lower_bounds.push_back(lower_bound); + model.variables_upper_bounds.push_back(upper_bound); + model.variables_types.push_back(type); + model.objective_coefficients.push_back(0.0); + return model.variables_lower_bounds.size() - 1; + }; + auto add_constraint = []( + mathoptsolverscmake::MathOptModel& model, + double lower_bound, + double upper_bound, + const std::vector>& elements) + { + model.constraints_starts.push_back(model.elements_variables.size()); + model.constraints_lower_bounds.push_back(lower_bound); + model.constraints_upper_bounds.push_back(upper_bound); + for (const auto& element: elements) { + model.elements_variables.push_back(element.first); + model.elements_coefficients.push_back(element.second); + } + }; + // Build the MILP of a rotation combination, restricted to the items + // 'active' (all the items if it is empty); the positions of the other + // items are free. + auto build_model = [&]( + const std::vector& rotation_ids, + const std::vector& active = {}) + { + auto is_active = [&active](ItemPos item_pos) + { + return active.empty() || active[item_pos]; + }; + mathoptsolverscmake::MathOptModel model; + model.objective_direction = mathoptsolverscmake::ObjectiveDirection::Minimize; + + // Positions of the reference points. + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + const ItemTypeRotationData& rotation = rotations[sorted_item_type_ids[item_pos]][rotation_ids[item_pos]]; + add_variable(model, rotation.x_min, rotation.x_max, mathoptsolverscmake::VariableType::Continuous); + add_variable(model, rotation.y_min, rotation.y_max, mathoptsolverscmake::VariableType::Continuous); + } + + // Symmetry breaking: identical items are sorted by x. + for (ItemPos item_pos = 0; item_pos + 1 < number_of_items; ++item_pos) { + if (sorted_item_type_ids[item_pos] != sorted_item_type_ids[item_pos + 1] + || rotation_ids[item_pos] != rotation_ids[item_pos + 1] + || !is_active(item_pos) + || !is_active(item_pos + 1)) { + continue; + } + add_constraint( + model, + -std::numeric_limits::infinity(), + 0.0, + {{2 * item_pos, 1.0}, {2 * (item_pos + 1), -1.0}}); + } + + // Non-overlap constraints. + for (ItemPos item_pos_1 = 0; item_pos_1 < number_of_items; ++item_pos_1) { + if (!is_active(item_pos_1)) + continue; + for (ItemPos item_pos_2 = item_pos_1 + 1; item_pos_2 < number_of_items; ++item_pos_2) { + if (!is_active(item_pos_2)) + continue; + const PairData& pair = pair_data( + item_pos_1, + item_pos_2, + rotation_ids[item_pos_1], + rotation_ids[item_pos_2]); + if (!pair.interact) + continue; + // Exactly one piece. + std::vector> elements; + for (const Piece& piece: pair.pieces) { + int piece_variable_id = add_variable(model, 0, 1, mathoptsolverscmake::VariableType::Binary); + elements.push_back({piece_variable_id, 1.0}); + add_piece_constraints( + model, + item_pos_1, + item_pos_2, + piece, + piece_variable_id, + {pair.x_min, pair.x_max, pair.y_min, pair.y_max}); + } + add_constraint(model, 1.0, 1.0, elements); + } + } + return model; + }; + + // Solve a MILP; 'stop' interrupts it. + std::atomic stop(false); + auto solve_model = [&]( + const mathoptsolverscmake::MathOptModel& model, + std::vector& values) -> MilpNfpStatus + { + if (parameters.solver == mathoptsolverscmake::SolverName::Highs) { +#ifdef HIGHS_FOUND + Highs highs; + mathoptsolverscmake::reduce_printout(highs); + mathoptsolverscmake::set_time_limit(highs, parameters.timer.remaining_time()); + mathoptsolverscmake::load(highs, model); + highs.setCallback([&stop, ¶meters]( + const int callback_type, + const std::string&, + const HighsCallbackOutput*, + HighsCallbackInput* highs_input, + void*) + { + if (callback_type != HighsCallbackType::kCallbackMipInterrupt) + return; + if (stop || parameters.timer.needs_to_end()) + highs_input->user_interrupt = 1; + }, + nullptr); + highs.startCallback(HighsCallbackType::kCallbackMipInterrupt); + mathoptsolverscmake::solve(highs); + HighsModelStatus status = highs.getModelStatus(); + if (status == HighsModelStatus::kInfeasible) + return MilpNfpStatus::Infeasible; + if (status == HighsModelStatus::kOptimal) { + values = highs.getSolution().col_value; + return MilpNfpStatus::Feasible; + } + return MilpNfpStatus::Unknown; +#else + throw std::invalid_argument(FUNC_SIGNATURE); +#endif + } else { + throw std::invalid_argument(FUNC_SIGNATURE); + } + }; + + // Prune the rotation combinations. + std::vector> kept_combinations; + for (const std::vector& combination: combinations) { + if (parameters.timer.needs_to_end()) { + output.status = MilpNfpStatus::Unknown; + return output; + } + output.number_of_rotation_combinations++; + if (prune(combination)) { + output.number_of_rotation_combinations_pruned++; + } else { + kept_combinations.push_back(combination); + } + } + for (const std::vector& combination: kept_combinations) { + for (ItemPos item_pos_1 = 0; item_pos_1 < number_of_items; ++item_pos_1) { + for (ItemPos item_pos_2 = item_pos_1 + 1; item_pos_2 < number_of_items; ++item_pos_2) { + output.maximum_number_of_pieces = (std::max)( + output.maximum_number_of_pieces, + (Counter)pair_data( + item_pos_1, + item_pos_2, + combination[item_pos_1], + combination[item_pos_2]).pieces.size()); + } + } + } + if (kept_combinations.empty()) { + output.status = MilpNfpStatus::Infeasible; + return output; + } + + // Solve the MILPs of the kept combinations, in parallel. Stop as soon as + // one isn't proven infeasible. + // + // A combination is infeasible if one of its sub-combinations without one + // of the items is. These are checked first: they are cheaper, and shared + // by several combinations. Their statuses, and the ones of the + // combinations, are kept in the cache, so that they are also reused by + // the next calls. + std::atomic next_combination_pos(0); + std::atomic number_of_milps(0); + std::atomic number_of_sub_combination_milps(0); + std::atomic number_of_rotation_combinations_pruned_by_sub_combinations(0); + std::mutex status_mutex; + MilpNfpStatus status = MilpNfpStatus::Infeasible; + auto combination_key = [&]( + const std::vector& rotation_ids, + const std::vector& active) + { + MilpNfpCombinationKey key; + key.first = bin_type_id; + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) + if (active.empty() || active[item_pos]) + key.second.push_back({sorted_item_type_ids[item_pos], rotation_ids[item_pos]}); + std::sort(key.second.begin(), key.second.end()); + return key; + }; + auto cached_status = [&cache_data](const MilpNfpCombinationKey& key) + { + std::lock_guard lock(cache_data.combinations_statuses_mutex); + auto it = cache_data.combinations_statuses.find(key); + return (it == cache_data.combinations_statuses.end())? + MilpNfpStatus::Unknown: + it->second; + }; + auto cache_status = [&cache_data]( + const MilpNfpCombinationKey& key, + MilpNfpStatus combination_status) + { + if (combination_status == MilpNfpStatus::Unknown) + return; + std::lock_guard lock(cache_data.combinations_statuses_mutex); + cache_data.combinations_statuses[key] = combination_status; + }; + auto worker = [&]() + { + for (;;) { + if (stop) + return; + Counter combination_pos = next_combination_pos++; + if (combination_pos >= (Counter)kept_combinations.size()) + return; + const std::vector& combination = kept_combinations[combination_pos]; + MilpNfpCombinationKey key = combination_key(combination, {}); + if (cached_status(key) == MilpNfpStatus::Infeasible) + continue; + + // Sub-combinations without one of the items. + bool infeasible_sub_combination = false; + if (parameters.check_sub_combinations && number_of_items >= 3) { + for (ItemPos removed_item_pos = 0; + removed_item_pos < number_of_items; + ++removed_item_pos) { + // Removing an item identical to the previous one gives + // the same sub-combination. + if (removed_item_pos > 0 + && sorted_item_type_ids[removed_item_pos] == sorted_item_type_ids[removed_item_pos - 1] + && combination[removed_item_pos] == combination[removed_item_pos - 1]) { + continue; + } + std::vector active(number_of_items, true); + active[removed_item_pos] = false; + MilpNfpCombinationKey sub_key = combination_key(combination, active); + MilpNfpStatus sub_status = cached_status(sub_key); + if (sub_status == MilpNfpStatus::Unknown) { + number_of_sub_combination_milps++; + std::vector sub_values; + sub_status = solve_model(build_model(combination, active), sub_values); + if (stop) + return; + cache_status(sub_key, sub_status); + } + if (sub_status == MilpNfpStatus::Infeasible) { + infeasible_sub_combination = true; + break; + } + } + } + if (infeasible_sub_combination) { + number_of_rotation_combinations_pruned_by_sub_combinations++; + cache_status(key, MilpNfpStatus::Infeasible); + continue; + } + + number_of_milps++; + std::vector values; + MilpNfpStatus combination_status = solve_model(build_model(combination), values); + cache_status(key, combination_status); + if (combination_status != MilpNfpStatus::Infeasible) { + std::lock_guard lock(status_mutex); + // 'Feasible' is a definitive answer; 'Unknown' may come from + // the interruption of another thread. + if (status != MilpNfpStatus::Feasible) { + status = combination_status; + if (status == MilpNfpStatus::Feasible) { + // Positions of the items. + LengthDbl scale_value = instance.parameters().scale_value; + output.items.clear(); + for (ItemPos item_pos = 0; item_pos < number_of_items; ++item_pos) { + const ItemTypeRotationData& rotation = rotations[sorted_item_type_ids[item_pos]][combination[item_pos]]; + SolutionItem item; + item.item_type_id = sorted_item_type_ids[item_pos]; + item.bl_corner.x = values[2 * item_pos] / scale_value; + item.bl_corner.y = values[2 * item_pos + 1] / scale_value; + item.angle = rotation.angle; + item.mirror = rotation.mirror; + output.items.push_back(item); + } + } + } + stop = true; + return; + } + } + }; + Counter number_of_threads = (std::max)((Counter)1, (std::min)( + parameters.number_of_threads, + (Counter)kept_combinations.size())); + std::vector threads; + for (Counter thread_id = 1; thread_id < number_of_threads; ++thread_id) + threads.push_back(std::thread(worker)); + worker(); + for (std::thread& thread: threads) + thread.join(); + output.number_of_milps = number_of_milps; + output.number_of_sub_combination_milps = number_of_sub_combination_milps; + output.number_of_rotation_combinations_pruned_by_sub_combinations + = number_of_rotation_combinations_pruned_by_sub_combinations; + output.status = status; + return output; +} + +bool packingsolver::irregular::milp_nfp_solution( + const Instance& instance, + BinTypeId bin_type_id, + const MilpNfpOutput& output, + Solution& solution) +{ + if (output.status != MilpNfpStatus::Feasible + || output.items.empty() + || instance.parameters().item_item_minimum_spacing > 0 + || !instance.bin_type(bin_type_id).fixed_items.empty()) { + return false; + } + SolutionBuilder solution_builder(instance); + BinPos bin_pos = solution_builder.add_bin(bin_type_id, 1); + for (const SolutionItem& item: output.items) { + solution_builder.add_item( + bin_pos, + item.item_type_id, + item.bl_corner, + item.angle, + item.mirror); + } + Solution new_solution = solution_builder.build(); + Solution::OverlappingItems overlapping_items = new_solution.compute_overlapping_items(bin_pos); + if (!overlapping_items.item_border_pairs.empty() + || !overlapping_items.item_defect_pairs.empty() + || !overlapping_items.item_item_pairs.empty() + || !overlapping_items.items_outside_bin.empty()) { + return false; + } + solution = new_solution; + return true; +} diff --git a/src/irregular/milp_nfp.hpp b/src/irregular/milp_nfp.hpp new file mode 100644 index 000000000..c6712ad8c --- /dev/null +++ b/src/irregular/milp_nfp.hpp @@ -0,0 +1,182 @@ +/** + * MILP NFP + * + * Prove that a set of items doesn't fit in a bin, with a mixed-integer linear + * program based on the no-fit polygons of the items. + * + * The rotations of the items are enumerated. For a rotation of each item: + * - The reference point of item i must be in its inner-fit rectangle IFP_i: + * the positions where its bounding box is in the bounding box of the bin + * (minus the item-bin spacing). + * - For a pair of items (i, j), the relative position d = p_j - p_i must be + * in R_ij = IFP_j - IFP_i, and outside the interior of the no-fit polygon + * NFP_ij. The region F_ij = R_ij \ int(NFP_ij) is partitioned into convex + * pieces, and a binary variable selects the piece containing d. The + * constraints of the edges of a piece are relaxed with big-M coefficients + * when the piece isn't selected. + * The set of items doesn't fit if the MILP of every rotation combination is + * infeasible. These MILPs are solved in parallel. + * + * Before solving the MILP of a rotation combination, the core widening may + * prove it infeasible. The core of an item is the part of its y-range which + * no other item can reach, given the regions F_ij. Since the rotations are + * fixed, the horizontal band of the core of an item, across the bin, contains + * no other item, so the item can be widened to the width of the bin on its + * core. The cores of different items are disjoint, so the rotation + * combination is infeasible if the sum of the widened areas exceeds the area + * of the bin. + * + * A rotation combination is also infeasible if one of its sub-combinations + * without one of the items is. These are checked first: their MILPs are + * cheaper, and each of them is shared by several combinations. The statuses + * of the combinations and sub-combinations are kept in the cache, so that + * the next calls reuse them. + * + * The exact fits (for example, an item exactly in a notch of another one) + * are feasible positions of null area strictly inside the no-fit polygon: + * line segments and points, returned by shape::no_fit_polygon. Each of them + * is an additional convex piece of F_ij. + * + * The model is a relaxation, so that an infeasible MILP is a proof: + * - The circular arcs of the regions F_ij are approximated by line segments + * outside of them. + * - The shape of the bin is replaced by its bounding box, and the defects, + * the fixed items and the item-item spacing are ignored. + * - The rotations must be discrete; otherwise, nothing is proven. + */ + +#pragma once + +#include "packingsolver/irregular/solution.hpp" + +#include "mathoptsolverscmake/mathopt.hpp" + +#include + +namespace packingsolver +{ +namespace irregular +{ + +enum class MilpNfpStatus +{ + /** Proven: the items don't fit in the bin. */ + Infeasible, + + /** + * The relaxation is feasible for some rotation combination, so the items + * may fit in the bin. + */ + Feasible, + + /** Not proven, because of the time limit or of a continuous rotation. */ + Unknown, +}; + +struct MilpNfpOutput +{ + /** Status. */ + MilpNfpStatus status = MilpNfpStatus::Unknown; + + /** Number of rotation combinations considered. */ + Counter number_of_rotation_combinations = 0; + + /** + * Number of rotation combinations proven infeasible without a MILP, + * because a pair of items doesn't fit or by the core widening. + */ + Counter number_of_rotation_combinations_pruned = 0; + + /** Number of MILPs of rotation combinations solved. */ + Counter number_of_milps = 0; + + /** Number of MILPs of sub-combinations solved. */ + Counter number_of_sub_combination_milps = 0; + + /** + * Number of rotation combinations proven infeasible by one of their + * sub-combinations. + */ + Counter number_of_rotation_combinations_pruned_by_sub_combinations = 0; + + /** Maximum number of convex pieces of a pair of items. */ + Counter maximum_number_of_pieces = 0; + + /** + * If the status is 'Feasible', the positions of the items in a solution + * of the relaxation (in the original coordinates). + * + * They are only a packing up to the relaxation: the shape of the bin, + * its defects, its fixed items and the item-item spacing are ignored. + */ + std::vector items; +}; + +/** + * Data reused between calls of 'milp_nfp' on the same instance: the convex + * pieces of the pairs of item types in each of their rotations, which are + * expensive to compute. + */ +class MilpNfpCache +{ + +public: + + MilpNfpCache(); + + ~MilpNfpCache(); + + struct Data; + + std::unique_ptr data_; +}; + +struct MilpNfpParameters: optimizationtools::Parameters +{ + /** MILP solver. */ + mathoptsolverscmake::SolverName solver + = mathoptsolverscmake::SolverName::Highs; + + /** + * Number of threads: the MILPs of the rotation combinations are solved + * in parallel. + */ + Counter number_of_threads = 4; + + /** + * Before solving the MILP of a rotation combination, check its + * sub-combinations without one of the items. + */ + bool check_sub_combinations = true; + + /** Cache, kept between calls on the same instance (optional). */ + MilpNfpCache* cache = nullptr; +}; + +/** + * Try to prove that the items of 'item_type_ids' (one entry per copy) don't + * fit in a bin of type 'bin_type_id'. + */ +MilpNfpOutput milp_nfp( + const Instance& instance, + BinTypeId bin_type_id, + const std::vector& item_type_ids, + const MilpNfpParameters& parameters = {}); + +/** + * Build the solution, with a single bin of type 'bin_type_id', of the + * positions of the items of a 'Feasible' output (see 'MilpNfpOutput::items'), + * and return 'true' if it is feasible. + * + * The solution is only checked for overlaps, so it isn't built if the items + * must be spaced or if the bin has fixed items, which the MILP NFP algorithm + * ignores. + */ +bool milp_nfp_solution( + const Instance& instance, + BinTypeId bin_type_id, + const MilpNfpOutput& output, + Solution& solution); + +} +} diff --git a/src/irregular/optimize.cpp b/src/irregular/optimize.cpp index 0a1ea3dce..43a4c956e 100644 --- a/src/irregular/optimize.cpp +++ b/src/irregular/optimize.cpp @@ -8,6 +8,8 @@ #include "irregular/tree_search_periodic_packing.hpp" #include "irregular/tree_search_maximal_spaces.hpp" #include "irregular/milp_raster.hpp" +#include "irregular/benders_decomposition.hpp" +#include "irregular/milp_nfp.hpp" #include "irregular/local_search.hpp" #include "algorithms/dichotomic_search.hpp" #include "algorithms/sequential_value_correction.hpp" @@ -737,7 +739,7 @@ void optimize_column_generation( AlgorithmFormatter& algorithm_formatter) { ColumnGenerationPricingFunction pricing_function - = [&algorithm_formatter, ¶meters](const Instance& kp_instance, PricingType) + = [&algorithm_formatter, ¶meters](const Instance& kp_instance, PricingType pricing_type) { OptimizeParameters kp_parameters; kp_parameters.seed = parameters.seed; @@ -754,6 +756,17 @@ void optimize_column_generation( = parameters.column_generation_subproblem_tree_search_queue_size; kp_parameters.linear_programming_solver_name = parameters.linear_programming_solver_name; kp_parameters.local_search_weighting_scheme = parameters.local_search_weighting_scheme; + // 'PricingType::Dual' calls are rare and exist to prove a bound: + // force the Benders decomposition alone, with the MILP NFP + // algorithm in its subproblems so that its cuts, and so its + // bound, are proven. In 'Exact' mode, also solved in 'Exact' + // mode so that the bound is actually proven. + if (pricing_type == PricingType::Dual) { + if (parameters.optimization_mode == OptimizationMode::Exact) + kp_parameters.optimization_mode = OptimizationMode::Exact; + kp_parameters.use_benders_decomposition = true; + kp_parameters.benders_decomposition_use_milp_nfp = true; + } return optimize(kp_instance, kp_parameters); }; @@ -763,6 +776,7 @@ void optimize_column_generation( cg_parameters.timer.add_end_boolean(&algorithm_formatter.end_boolean()); cg_parameters.optimization_mode = parameters.optimization_mode; cg_parameters.linear_programming_solver_name = parameters.linear_programming_solver_name; + cg_parameters.pricing_function_has_dual_bound = true; cg_parameters.new_solution_callback = [&algorithm_formatter]( const irregular::Output& ps_output) { @@ -839,6 +853,74 @@ void optimize_milp_raster( milp_raster(instance, milp_raster_parameters); } +void optimize_benders_decomposition( + const Instance& instance, + const OptimizeParameters& parameters, + AlgorithmFormatter& algorithm_formatter) +{ + BendersDecompositionParameters bd_parameters; + bd_parameters.verbosity_level = 0; + bd_parameters.linear_programming_solver_name = parameters.linear_programming_solver_name; + bd_parameters.timer = parameters.timer; + bd_parameters.timer.add_end_boolean(&algorithm_formatter.end_boolean()); + bd_parameters.optimization_mode = parameters.optimization_mode; + bd_parameters.not_anytime_maximum_number_of_iterations + = parameters.not_anytime_benders_decomposition_number_of_iterations; + bd_parameters.subproblem_queue_size + = parameters.benders_decomposition_subproblem_tree_search_queue_size; + // In 'Exact' mode, the MILP NFP algorithm is used so that the cuts are + // proven. + bd_parameters.subproblem_use_milp_nfp = parameters.benders_decomposition_use_milp_nfp + || parameters.optimization_mode == OptimizationMode::Exact; + bd_parameters.new_solution_callback = [&algorithm_formatter]( + const irregular::Output& output) + { + const BendersDecompositionOutput& bd_output + = static_cast(output); + std::stringstream ss; + ss << "BD " << bd_output.number_of_iterations; + algorithm_formatter.update_solution(bd_output.solution_pool.best(), ss.str()); + algorithm_formatter.update_bounds(bd_output); + }; + benders_decomposition(instance, bd_parameters); +} + +void optimize_milp_nfp( + const Instance& instance, + const OptimizeParameters& parameters, + AlgorithmFormatter& algorithm_formatter) +{ + BinTypeId bin_type_id = 0; + while (instance.bin_type(bin_type_id).copies == 0) + bin_type_id++; + std::vector item_type_ids; + 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 = item_type.copies_fixed; copy < item_type.copies; ++copy) + item_type_ids.push_back(item_type_id); + } + MilpNfpParameters milp_nfp_parameters; + milp_nfp_parameters.verbosity_level = 0; + milp_nfp_parameters.timer = parameters.timer; + milp_nfp_parameters.timer.add_end_boolean(&algorithm_formatter.end_boolean()); + if (parameters.optimization_mode == OptimizationMode::NotAnytimeSequential) + milp_nfp_parameters.number_of_threads = 1; + MilpNfpOutput milp_nfp_output = milp_nfp( + instance, + bin_type_id, + item_type_ids, + milp_nfp_parameters); + if (milp_nfp_output.status == MilpNfpStatus::Infeasible) { + algorithm_formatter.update_is_proven_infeasible(); + } else { + Solution solution(instance); + if (milp_nfp_solution(instance, bin_type_id, milp_nfp_output, solution)) + algorithm_formatter.update_solution(solution, "MILP NFP"); + } +} + /** * Area of the bin of a single-bin instance which is left for the items to * place: its area minus the areas of its fixed items and of its defects @@ -1035,6 +1117,20 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( bool use_dichotomic_search = parameters.use_dichotomic_search; bool use_column_generation = parameters.use_column_generation; bool use_milp_raster = parameters.use_milp_raster; + bool use_benders_decomposition = parameters.use_benders_decomposition; + bool use_milp_nfp = parameters.use_milp_nfp; + // The MILP NFP algorithm only supports the 'Feasibility' objective with a + // single bin. + if (instance.objective() != Objective::Feasibility + || instance.number_of_bins() != 1) { + use_milp_nfp = false; + } + // Benders decomposition only supports these objectives. + if (instance.objective() != Objective::Knapsack + && instance.objective() != Objective::BinPacking + && instance.objective() != Objective::VariableSizedBinPacking) { + use_benders_decomposition = false; + } if (instance.number_of_bins() <= 1) { // Disable algorithms which are not available for this objective. use_sequential_single_knapsack = false; @@ -1051,6 +1147,8 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( } // Automatic selection. if (!use_tree_search + && !use_benders_decomposition + && !use_milp_nfp && !use_tree_search_periodic_packing && !use_tree_search_maximal_spaces && !use_local_search_linear_programming @@ -1089,6 +1187,16 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( < parameters.periodic_packing_max_items_threshold; if (instance.objective() != Objective::Knapsack) use_local_search_direct_trigonometry = true; + // In 'Exact' mode, also run the algorithms which can prove + // optimality. + if (parameters.optimization_mode == OptimizationMode::Exact) { + if (instance.objective() == Objective::Knapsack) + use_benders_decomposition = true; + if (instance.objective() == Objective::Feasibility + && instance.number_of_bins() == 1) { + use_milp_nfp = true; + } + } } } else if (instance.objective() == Objective::Feasibility) { // Disable algorithms which are not available for this objective. @@ -1128,6 +1236,7 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( use_tree_search_periodic_packing = false; // Automatic selection. if (!use_tree_search + && !use_benders_decomposition && !use_milp_raster && !use_sequential_single_knapsack && !use_sequential_value_correction @@ -1170,6 +1279,7 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( use_milp_raster = false; // Automatic selection. if (!use_tree_search + && !use_benders_decomposition && !use_tree_search_periodic_packing && !use_local_search_linear_programming && !use_local_search_nonlinear_programming @@ -1219,6 +1329,7 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( } // Automatic selection. if (!use_tree_search + && !use_benders_decomposition && !use_local_search_linear_programming && !use_local_search_nonlinear_programming && !use_local_search_direct_trigonometry @@ -1476,6 +1587,32 @@ packingsolver::irregular::Output packingsolver::irregular::optimize( *context.second); }); } + // Benders decomposition. + if (use_benders_decomposition) { + exception_ptr_list.push_front(std::exception_ptr()); + std::exception_ptr& exception_ptr = exception_ptr_list.front(); + auto context = task_context(); + tasks.push_back([&exception_ptr, &instance, context]() { + wrapper( + exception_ptr, + instance, + *context.first, + *context.second); + }); + } + // MILP NFP. + if (use_milp_nfp) { + exception_ptr_list.push_front(std::exception_ptr()); + std::exception_ptr& exception_ptr = exception_ptr_list.front(); + auto context = task_context(); + tasks.push_back([&exception_ptr, &instance, context]() { + wrapper( + exception_ptr, + instance, + *context.first, + *context.second); + }); + } run(tasks, algorithm_formatter, parameters); for (std::exception_ptr exception_ptr: exception_ptr_list) if (exception_ptr) diff --git a/src/irregular/reduction.cpp b/src/irregular/reduction.cpp index e2ffdea8b..250c88967 100644 --- a/src/irregular/reduction.cpp +++ b/src/irregular/reduction.cpp @@ -366,6 +366,7 @@ Instance Reduction::reduction_to_instance( { InstanceBuilder instance_builder; instance_builder.set_objective(original_instance_->objective()); + instance_builder.set_knapsack_goal(original_instance_->knapsack_goal()); instance_builder.set_parameters(original_instance_->parameters()); instance_builder.set_feasibility_callback(original_instance_->feasibility_callback()); diff --git a/test/irregular/CMakeLists.txt b/test/irregular/CMakeLists.txt index 3e4545c3b..837ba8563 100644 --- a/test/irregular/CMakeLists.txt +++ b/test/irregular/CMakeLists.txt @@ -2,6 +2,8 @@ add_executable(PackingSolver_irregular_test) target_sources(PackingSolver_irregular_test PRIVATE irregular_test.cpp milp_raster_test.cpp + milp_nfp_test.cpp + benders_decomposition_test.cpp local_search_test.cpp reduction_test.cpp sequential_feasibility_test.cpp diff --git a/test/irregular/benders_decomposition_test.cpp b/test/irregular/benders_decomposition_test.cpp new file mode 100644 index 000000000..8ddc6d68b --- /dev/null +++ b/test/irregular/benders_decomposition_test.cpp @@ -0,0 +1,177 @@ +#include "packingsolver/irregular/instance_builder.hpp" +#include "packingsolver/irregular/optimize.hpp" + +#include + +using namespace packingsolver; +using namespace packingsolver::irregular; + +namespace +{ + +/** + * Add an item type 'width' x 'height', which can't be rotated. + */ +ItemTypeId add_rectangle_item_type( + InstanceBuilder& instance_builder, + LengthDbl width, + LengthDbl height, + Profit profit, + ItemPos copies) +{ + ItemShape item_shape; + item_shape.shape_orig.shape = shape::build_rectangle(0, width, 0, height); + ItemTypeId item_type_id = instance_builder.add_item_type({item_shape}); + instance_builder.set_item_type_profit(item_type_id, profit); + instance_builder.set_item_type_copies(item_type_id, copies); + return item_type_id; +} + +OptimizeParameters benders_decomposition_parameters(bool use_milp_nfp) +{ + OptimizeParameters parameters; + parameters.verbosity_level = 0; + parameters.optimization_mode = OptimizationMode::NotAnytimeSequential; + parameters.use_benders_decomposition = true; + parameters.benders_decomposition_use_milp_nfp = use_milp_nfp; + return parameters; +} + +} + +/* + * Three 60 x 40 items in 100 x 100 bins: by area, they fit in a single bin, + * but two of them can't be side by side, so they need two bins. + */ + +TEST(IrregularBendersDecomposition, BinPacking) +{ + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::BinPacking); + BinTypeId bin_type_id = instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + instance_builder.set_bin_type_copies(bin_type_id, 3); + add_rectangle_item_type(instance_builder, 60, 40, 1, 3); + Instance instance = instance_builder.build(); + + irregular::Output output = optimize(instance, benders_decomposition_parameters(true)); + EXPECT_EQ(output.solution_pool.best().feasible(), true); + EXPECT_EQ(output.solution_pool.best().number_of_bins(), 2); + EXPECT_EQ(output.bin_packing_bound, 2); +} + +TEST(IrregularBendersDecomposition, BinPackingWithoutMilpNfp) +{ + // Without the MILP NFP algorithm, the subproblems don't prove that the + // bins are infeasible, but the solution is still found. + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::BinPacking); + BinTypeId bin_type_id = instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + instance_builder.set_bin_type_copies(bin_type_id, 3); + add_rectangle_item_type(instance_builder, 60, 40, 1, 3); + Instance instance = instance_builder.build(); + + irregular::Output output = optimize(instance, benders_decomposition_parameters(false)); + EXPECT_EQ(output.solution_pool.best().feasible(), true); + EXPECT_EQ(output.solution_pool.best().number_of_bins(), 2); +} + +TEST(IrregularBendersDecomposition, Knapsack) +{ + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::Knapsack); + instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + add_rectangle_item_type(instance_builder, 60, 40, 10, 3); + Instance instance = instance_builder.build(); + + irregular::Output output = optimize(instance, benders_decomposition_parameters(true)); + EXPECT_EQ(output.solution_pool.best().profit(), 20); + EXPECT_EQ(output.knapsack_bound, 20); +} + +TEST(IrregularBendersDecomposition, VariableSizedBinPacking) +{ + // A 100 x 50 bin (cost 4) holds two 60 x 40 items by area, but only one + // geometrically; a 100 x 100 bin (cost 10) holds two. The optimal + // solution uses three 100 x 50 bins. + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::VariableSizedBinPacking); + BinTypeId large_bin_type_id = instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + instance_builder.set_bin_type_cost(large_bin_type_id, 10); + instance_builder.set_bin_type_copies(large_bin_type_id, 3); + BinTypeId small_bin_type_id = instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 50)); + instance_builder.set_bin_type_cost(small_bin_type_id, 4); + instance_builder.set_bin_type_copies(small_bin_type_id, 3); + add_rectangle_item_type(instance_builder, 60, 40, 1, 3); + Instance instance = instance_builder.build(); + + irregular::Output output = optimize(instance, benders_decomposition_parameters(true)); + EXPECT_EQ(output.solution_pool.best().feasible(), true); + EXPECT_EQ(output.solution_pool.best().cost(), 12); + EXPECT_EQ(output.variable_sized_bin_packing_bound, 12); +} + +TEST(IrregularBendersDecomposition, KnapsackExact) +{ + // In 'Exact' mode, the automatic selection runs the Benders + // decomposition for a single bin knapsack, which proves the bound. + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::Knapsack); + instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + add_rectangle_item_type(instance_builder, 60, 40, 10, 3); + Instance instance = instance_builder.build(); + + OptimizeParameters parameters; + parameters.verbosity_level = 0; + parameters.optimization_mode = OptimizationMode::Exact; + irregular::Output output = optimize(instance, parameters); + EXPECT_EQ(output.solution_pool.best().profit(), 20); + EXPECT_EQ(output.knapsack_bound, 20); +} + +TEST(IrregularColumnGeneration, BinPackingDualPricing) +{ + // Five 60 x 40 items in 100 x 100 bins: by area, they fit in two bins, + // but a bin holds at most two of them. The 'Dual' pricing (a Benders + // decomposition with the MILP NFP algorithm) proves it, so the bound of + // the column generation is 3. + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::BinPacking); + BinTypeId bin_type_id = instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + instance_builder.set_bin_type_copies(bin_type_id, 5); + add_rectangle_item_type(instance_builder, 60, 40, 1, 5); + Instance instance = instance_builder.build(); + + OptimizeParameters parameters; + parameters.verbosity_level = 0; + parameters.use_column_generation = true; + irregular::Output output = optimize(instance, parameters); + EXPECT_EQ(output.solution_pool.best().number_of_bins(), 3); + EXPECT_EQ(output.bin_packing_bound, 3); +} + +TEST(IrregularBendersDecomposition, KnapsackGoal) +{ + // With a knapsack goal of 25, the bound 20 proves that it can't be + // reached; with a knapsack goal of 15, a solution of profit 20 reaches + // it. + for (Profit knapsack_goal: {25.0, 15.0}) { + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::Knapsack); + instance_builder.set_knapsack_goal(knapsack_goal); + instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + add_rectangle_item_type(instance_builder, 60, 40, 10, 3); + Instance instance = instance_builder.build(); + + irregular::Output output(instance); + output.knapsack_bound = 30; + EXPECT_FALSE(output.is_proven_optimal()); + if (knapsack_goal > 20) { + output.knapsack_bound = 20; + EXPECT_TRUE(output.is_proven_optimal()); + } else { + output = optimize(instance, benders_decomposition_parameters(true)); + EXPECT_GE(output.solution_pool.best().profit(), 15); + EXPECT_TRUE(output.is_proven_optimal()); + } + } +} diff --git a/test/irregular/milp_nfp_test.cpp b/test/irregular/milp_nfp_test.cpp new file mode 100644 index 000000000..e8c007610 --- /dev/null +++ b/test/irregular/milp_nfp_test.cpp @@ -0,0 +1,186 @@ +#include "packingsolver/irregular/instance_builder.hpp" +#include "packingsolver/irregular/optimize.hpp" +#include "irregular/milp_nfp.hpp" +#include "irregular/solution_builder.hpp" + +#include + +using namespace packingsolver; +using namespace packingsolver::irregular; + +namespace +{ + +struct MilpNfpTestItemType +{ + Shape shape; + std::vector angles; +}; + +Instance build_instance( + LengthDbl bin_width, + LengthDbl bin_height, + const std::vector& item_types) +{ + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::Feasibility); + instance_builder.add_bin_type(shape::build_rectangle(0, bin_width, 0, bin_height)); + for (const MilpNfpTestItemType& item_type: item_types) { + ItemShape item_shape; + item_shape.shape_orig.shape = item_type.shape; + ItemTypeId item_type_id = instance_builder.add_item_type({item_shape}); + for (Angle angle: item_type.angles) + instance_builder.add_item_type_allowed_rotation(item_type_id, angle, angle, false); + } + return instance_builder.build(); +} + +MilpNfpStatus status( + const Instance& instance, + const std::vector& item_type_ids) +{ + MilpNfpParameters parameters; + parameters.verbosity_level = 0; + return milp_nfp(instance, 0, item_type_ids, parameters).status; +} + +/** + * Step of size 20 x 20: two copies, one of them rotated by 180 degrees, tile + * a 20 x 30 rectangle, at a single relative position. + */ +Shape build_step() +{ + return shape::build_shape({{0, 0}, {20, 0}, {20, 20}, {10, 20}, {10, 10}, {0, 10}}); +} + +} + +TEST(IrregularMilpNfp, SquaresTooLarge) +{ + // Two 55 x 55 squares don't fit in a 100 x 100 bin. + Instance instance = build_instance(100, 100, {{shape::build_square(55), {0}}}); + EXPECT_EQ(status(instance, {0, 0}), MilpNfpStatus::Infeasible); +} + +TEST(IrregularMilpNfp, SquaresExactFit) +{ + // Four 50 x 50 squares exactly fit in a 100 x 100 bin, five don't. + Instance instance = build_instance(100, 100, {{shape::build_square(50), {0}}}); + EXPECT_EQ(status(instance, {0, 0}), MilpNfpStatus::Feasible); + EXPECT_EQ(status(instance, {0, 0, 0, 0}), MilpNfpStatus::Feasible); + EXPECT_EQ(status(instance, {0, 0, 0, 0, 0}), MilpNfpStatus::Infeasible); +} + +TEST(IrregularMilpNfp, StepsInterlocked) +{ + // With the rotation by 180 degrees, two steps exactly fit in a 20 x 30 + // bin, interlocked. + Instance instance = build_instance(20, 30, {{build_step(), {0, 180}}}); + EXPECT_EQ(status(instance, {0, 0}), MilpNfpStatus::Feasible); +} + +TEST(IrregularMilpNfp, StepsWithoutRotation) +{ + // Without the rotation, two steps don't fit in a 20 x 30 bin. + Instance instance = build_instance(20, 30, {{build_step(), {0}}}); + EXPECT_EQ(status(instance, {0, 0}), MilpNfpStatus::Infeasible); +} + +TEST(IrregularMilpNfp, Crosses) +{ + // Every placement of a cross of span 70 in a 100 x 100 bin covers the + // center of the bin, so two crosses don't fit, whereas one cross and a + // 25 x 25 square in a corner fit. + Shape cross = shape::build_shape({ + {20, 0}, {50, 0}, {50, 20}, {70, 20}, {70, 50}, {50, 50}, + {50, 70}, {20, 70}, {20, 50}, {0, 50}, {0, 20}, {20, 20}}); + Instance instance = build_instance(100, 100, { + {cross, {0}}, + {shape::build_square(25), {0}}}); + EXPECT_EQ(status(instance, {0, 0}), MilpNfpStatus::Infeasible); + EXPECT_EQ(status(instance, {0, 1}), MilpNfpStatus::Feasible); +} + +TEST(IrregularMilpNfp, CoreWidening) +{ + // Two 60 x 40 rectangles can't be side by side in a 100 x 100 bin, so + // each one is widened to 100 x 40; three of them don't fit, which the core + // widening proves without a MILP. Two 60 x 50 rectangles fit exactly. + Instance instance = build_instance(100, 100, { + {shape::build_rectangle(0, 60, 0, 40), {0}}, + {shape::build_rectangle(0, 60, 0, 50), {0}}}); + MilpNfpParameters parameters; + parameters.verbosity_level = 0; + MilpNfpOutput output = milp_nfp(instance, 0, {0, 0, 0}, parameters); + EXPECT_EQ(output.status, MilpNfpStatus::Infeasible); + EXPECT_EQ(output.number_of_milps, 0); + EXPECT_EQ(status(instance, {0, 0}), MilpNfpStatus::Feasible); + EXPECT_EQ(status(instance, {1, 1}), MilpNfpStatus::Feasible); +} + +TEST(IrregularMilpNfp, Symmetries) +{ + // The rotations by 0 and 180 degrees of a square are the same, and the + // ones of the (single) step are symmetric through the bin: a single + // rotation combination is left. The square fits in the notch of the + // step. + Instance instance = build_instance(20, 30, { + {build_step(), {0, 180}}, + {shape::build_square(10), {0, 180}}}); + MilpNfpParameters parameters; + parameters.verbosity_level = 0; + MilpNfpOutput output = milp_nfp(instance, 0, {0, 1}, parameters); + EXPECT_EQ(output.status, MilpNfpStatus::Feasible); + EXPECT_EQ(output.number_of_rotation_combinations, 1); +} + +TEST(IrregularMilpNfp, Packing) +{ + // When the relaxation is feasible, the positions of its solution are + // returned; here, without exact fits, they are a packing. + Instance instance = build_instance(100, 100, { + {build_step(), {0, 180}}, + {shape::build_square(30), {0}}, + {shape::build_rectangle(0, 60, 0, 25), {0}}}); + MilpNfpParameters parameters; + parameters.verbosity_level = 0; + MilpNfpOutput output = milp_nfp(instance, 0, {0, 0, 1, 2}, parameters); + ASSERT_EQ(output.status, MilpNfpStatus::Feasible); + ASSERT_EQ(output.items.size(), 4); + SolutionBuilder solution_builder(instance); + BinPos bin_pos = solution_builder.add_bin(0, 1); + for (const SolutionItem& item: output.items) { + solution_builder.add_item( + bin_pos, + item.item_type_id, + item.bl_corner, + item.angle, + item.mirror); + } + Solution solution = solution_builder.build(); + Solution::OverlappingItems overlapping_items = solution.compute_overlapping_items(bin_pos); + EXPECT_TRUE(overlapping_items.item_item_pairs.empty()); + EXPECT_TRUE(overlapping_items.item_border_pairs.empty()); + EXPECT_TRUE(overlapping_items.items_outside_bin.empty()); +} + +TEST(IrregularMilpNfp, OptimizeExactInfeasible) +{ + // In 'Exact' mode, the automatic selection runs the MILP NFP algorithm for + // a single bin feasibility problem, which proves that two 55 x 55 squares + // don't fit in a 100 x 100 bin. + InstanceBuilder instance_builder; + instance_builder.set_objective(Objective::Feasibility); + instance_builder.add_bin_type(shape::build_rectangle(0, 100, 0, 100)); + ItemShape item_shape; + item_shape.shape_orig.shape = shape::build_square(55); + ItemTypeId item_type_id = instance_builder.add_item_type({item_shape}); + instance_builder.set_item_type_copies(item_type_id, 2); + Instance instance = instance_builder.build(); + + OptimizeParameters parameters; + parameters.verbosity_level = 0; + parameters.optimization_mode = OptimizationMode::Exact; + irregular::Output output = optimize(instance, parameters); + EXPECT_TRUE(output.is_proven_infeasible); +}