Penlect / rectangle-packer

Rectangle packing program
MIT License
62 stars 16 forks source link

Sharing a recipe: optimal packing when allowing for rotations #17

Open Lucas-C opened 1 year ago

Lucas-C commented 1 year ago

Thanks to your library, I was able to optimize the packing of my library shelves on a wall at home:

proposition

Thank you! 👍 (I know, it looks simple enough to solve by hand, but it was fun using your lib and building a web visualization 😊)

In the process I used the following function to find the optimal rectangle packing while allowing for 90° rotations, and thought it could be useful to share it here:

from itertools import chain, combinations
from rpack import pack, packing_density, PackingImpossibleError

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def optimal_pack(sizes, max_width=None, max_height=None):
    best_sizes, best_positions, best_density = (), (), 0
    for rotated_sizes_indices in powerset(range(len(sizes))):
        sizes_with_rotations = [((height, width) if i in rotated_sizes_indices else (width, height))
                                for (i, (width, height)) in enumerate(sizes)]
        try:
            positions = pack(sizes_with_rotations, max_width=max_width, max_height=max_height)
        except PackingImpossibleError:
            continue
        density = packing_density(sizes, positions)
        if not best_density or density > best_density:
            best_sizes, best_positions, best_density = sizes_with_rotations, positions, density
    return best_sizes, best_positions
nhansendev commented 2 months ago

Thanks for sharing! I was surprised when the base-code didn't auto-rotate. Hopefully the author adds this functionality.

nhansendev commented 2 months ago

This problem was interesting to me so I also came up with my own methods of checking rotations, maximizing area usage, and packing onto multiple sheets: https://github.com/nhansendev/RectanglePack