Algorithm for fitting 2D polygons in an area? - algorithm

Is there a standard for this? Algorithm name?
Say:
I have 10 polygons of different sizes.
I have an area of specific size.
I want to know how to fill the most polygons in that area, and how they are fitted.
Note:
Polygons may be rotated depending on the restriction set.

One possible name is a Packing Problem. It is related to the Knapsack Problem. These problems tend to be NP-hard, and many require heuristics. If you can constrain the allowed forms of polygons and of the area, there may exist a more efficient algorithm for your special case.

You can have a look at "Dancing Links" in Wikipedia for Donald Knuth's solution to the exact cover problem - which includes tiling - your question can be looked at as a tiling problem

IF (that's a big if) all your polygons were rectangles, and the area into which they are to fit is also a rectangle, then this would be called bin-packing, Google will overwhelm you with information about this. If they're not then I guess that you are looking for a variant of bin-packing, and I guess some more that you are into an NP problem for which 'try and test' is about the best algorithm around.

Related

Divide an image by grouping similar pixels into rectangles

consider an image like this:
by grouping pixels by color into distinct rectangles, different configurations might be achieved, for example:
the goal is to find one of the best configurations, i.e. a configuration which has the least possible number of rectangles (rectangles sizes are not important).
any idea on how to design an efficient algorithm which is able to solve this problem?
EDIT:
i think the best answer is the one by #dshin, as they proved that this problem is a NP-HARD one so there probably isn't any efficient solution that is able to guarantee an optimal result.
other answers provide reasonable compromises to get an acceptable solution, but that won't always be the optimal one.
Each connected colored region is a rectilinear polygon that can be considered independently, and so your problem amounts to solving the minimum rectangle covering for rectilinear polygons. This is a well-studied problem that finds applications in some fields, like VLSI.
For convex rectilinear polygons, there is an algorithm that finds the optimal solution in polynomial time, described in this 1984 thesis.
The non-convex case is NP-hard (reference), so an efficient optimal solution likely does not exist. But there are several algorithms which produce good empirical results. This 1990 publication describes three separate algorithms, each of which are guaranteed to use at most twice as many rectangles as the optimal solution. This 2016 publication describes an algorithm that uses the common IP + LP relaxation technique, which apparently produces better results in real-life problem instances, although lacking in theoretical guarantees. Unfortunately, both publications are behind paywalls, and I haven't been able to find free resources that describe the algorithms.
If you are just looking for something reasonable, and your problem instances are not pathological in nature, then the algorithms described in other answers are probably good enough.
I don't have a proof but my feeling is a greedy approach should solve this problem:
Start on the upper left (or in whichever corner)
Expand rectangle 1px to the right as long as colors match
Expand rectangle 1px to the bottom as long as all colors in that row match
Line by line and column by column, find the next pixel that is not already part of a square (maybe keep track of visited pixels in a second array) and repeat 2 and 3.
You can switch lines and columns and go up and left or whatever instead and end up with different configurations, but from playing this through in my mind I think the number of rectangles should always be the same.
The idea here is based on the following links: Link 1 and Link 2.
In both the cases, the largest possible rectangle is computed within a given polygon/shape. Check both the above links for details.
We can extend the idea above to the problem at hand.
Steps:
Filter the image by color (say red)
Find the largest possible rectangle in the red region. After doing so mask it.
Repeat to find the next biggest rectangle until all the portions in red have been covered.
Repeat the above for every unique color.
Overview:

Distribute objects within a circle [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pack squares into circles?
I have a problem where I need to fit a bunch of different sized rectangles within a circle. All the rectangles must fit in the circle without overlapping each other and without overflowing the circle.
Assuming the rectangles can fit inside the circle how would one develop an algorithm to distribute them inside the circle?
All I can think of is to randomly distribute the rectangles over and over and test whether the conditions are met (brute-force).
It is a classic constraint problem, brute-force is one way to do it but there are other ways that can be better using things such as heuristics to help guide the algorithm to the solution. You would have to look up some constraint programming and bin packing papers on something like Google Scholar for some better algorithms.
Wikipedia has a good overview:
http://en.wikipedia.org/wiki/Packing_problem
As others have mentioned, an optimal solution (in say minimal area or uniform distriubtion) is likely to be NP-hard. Nevertheless, depending on your needs there are some great algorithms for packing differently sized rectangles into other rectangles. For example: Fast Optimizing Rectangle Packing Algorithm for Building CSS Sprites:
This article describes a fast algorithm to pack a series of rectangles of varying widths and heights into a single enclosing rectangle, with no overlap and in a way that minimizes the amount of wasted space in the enclosing rectangle. [...] shows step by step how the algorithm arrives at the optimal enclosing rectangle.
Note that in the above procedure the bounding rectangle is allowed to vary (nor am I convinced that the solution is the optimal enclosing rectangle). You can approximate a circle by breaking it up into discrete rectangles.
While not a complete solution to what you are looking for, I think this may be a good first step.

Fill arbitrary 2D shape with given set of rectangles

I have a set of rectangles and arbitrary shape in 2D space. The shape is not necessary a polygon (it may be a circle), and rectangles have different widths and heights. The task is to approximate the shape with rectangles as close as possible. I can't change rectangles dimensions, but rotation is permitted.
It sounds very similar to packing problem and covering problem but covering area is not rectangular...
I guess it's NP problem, and I'm pretty sure there should be some papers that show good heuristics to solve it, but I don't know what to google? Where should I start?
Update: One idea just came into my mind but I'm not sure if it's worth investigating. What if we consider bounding shape as a physical mold filled with water. Each rectangle is considered as a positively charged particle with size. Now drop the smallest rectangle to it. Then drop the next by size at random point. If rectangles too close they repel each other. Keep adding rectangles until all are used. Could this method work?
I think you could look for packing and automatic layout generation algorithms. Automatic VLSI layout generation algorithms might need similar things, just like textile layout questions...
This paper Hegedüs: Algorithms for covering polygons by rectangles seems to address a similar problem. And since this paper is from 1982, it might be interesting to look at the papers which cite this one. Additionally, this meeting seems to be discussing research problems related to this, so might be a starting point for keywords or names who do research in this idea.
I don't know if the computational geometry research has algorithms for your specific problem, or if these algorithms are easy/practical enough to implement. Here is how I would approach it if I had to do it without being able to look up previous work. This is just a direction, by far not a solution...
Formulate it as an optimization problem. You have discrete variables of which rectangles you choose (yes or no) and continuous variables (location and orientation of the triangles). Now you can set up two independent optimizations: a discrete optimization which picks the rectangles; and a continuous that optimizes for the location and orientation once rectangles are given. Interleave these two optimizations. Of course the difficulty lies in the formulation of optimizations, and designing your error energy such that it does not get stuck in some strange configurations (local minima). I'd try to get the continuous as a least squares problem such that I can use standard optimizations libraries.
I think this problem is suitable for solving with genetic algorithm and/or evolutionary strategy algorithm. I've done similar box packing problem with the help of evolutionary strategy algorithm of some kind. Check this out in my blog.
So if you will use such approach - encode into chromosomes box:
x coordinate
y coordinate
angle
Then try to minimize such fitness function-
y = w1 * box_intersection_area +
w2 * box_area_out_of_shape +
w3 * average_circle_radius_in_free_space
Choose weights w1,w2,w3 such as to affect importance of factors. When genetic algorithm will find partial solution - remove boxes which still overlaps together or are out of shape - and you will have at least legal (but not necessary optimal) solution.
good luck in this interesting problem !
It is NP hard indeed and since it has hi-tech application, reasonably efficients approximate strategies are not even in patents, let alone published papers.
The best you can do with a limited budget is to start by limiting the problem. Assume that all rectangles are exactly the same, Assume that all rectangles which are binary sub-divisions of your standard rectangle are also allowed since you can efficiently pre-pack them to fit your core division. For extra points you can also form several fixed schemas for gluing core rectangles to cover a few larger shapes with substantially different proportions. Assume that you can change dimensions of your standard rectangle/cell as long as the rest (pre-packing and gluing schema) remains the same - this gives you parameters to decide approximate size of the core rectangle based on rectangles you are given.
Now you can play with aspect ratios to approximate the error such limited system could guarantee. For the first iterations assume that it can have 50% error with a simple sub-division schema and then change schema to reduce the error but without increasing asymptotic complexity of pre-packing. At the end of the day you are always just assigning given rectangles to your pre-calculated and now fixed grid and binary sub-divisions - meaning you are not trying to do a layout or backtrack at all - you are always happy with the first approximate fit into the grid.
Work on defining classes of rectangles that pack well with your schema - that's again to keep the whole process inverted - you are never trying to actually fit what you are given - you are defining what you have to be given in order to fir it well - then you punt the rest as error since it is approximation.
Then you can try to do a bit more, but not much more - any slip into backtracking or nailing arbitrary small error and it's exponential.
If you are at a research facility and can get some supercomputer time - run a set of exhaustive searches with pathological mixes there just to see how optimal packing may look like and to see if you can derive a few more sub-division schemas and/or classes of rectangle sets.
That should be enough for the first 2 yrs or research :-)

Fitting rectangles together in optimal fashion

I was wondering if anyone knows of any algorithms suited to fitting together N number of rectangles of unknown size into the smallest possible containing rectangle.
By optimal I mean with reducing the amount of white space left over in the resulting containing rectangle.
I would like to use this to generate css sprites from a series of images.
Many Thanks,
Ian
I think what you describe is a variant of the "two dimensional bin packing" problem. The only difference is that you have the items and are trying to find the smallest rectangle.
This survey article is a good start.
Through packing images into square texture and Simon's answer I got to this link http://code.activestate.com/recipes/442299/
I did not check the recipe, but it seems to allow using non-square containers.
The only way to guarantee and optimal solution is to brute force the answer. This quickly becomes unmanagable for personal computers when you have several rectangles, and allow for the possibility of rotation.
Wikipedia has a good article on packing problem
http://en.wikipedia.org/wiki/Packing_problem
Here is a good description of a fast packing algorithm - http://www.codeproject.com/KB/web-image/rectanglepacker.aspx

How to find minimal amount of subdivisions

Imagine you have a canvas and in this canvas there are already some objects. How can you find the minimal way to cover the "uncovered" area with squares, not overlaying each other, completely filling the canvas.
In my case the "canvas" is a html-div container and the objects are nested div-containers.
Could look like this: http://www.encodechain.com/demo/200908_optimize.png
On the left there's the "start" and on the right there's on possible first "step"...
I know that there's an algorithm for this, but currently I can't remember the name.
The best I could find was this paper: Tiling a rectangle with the fewest squares.
The paper is an interesting read, though at times it delves deep into theory territory with talk of "universal constants". I am not certain whether the question of "can a rectangle of size m by n be tiled with k squares" is NP-complete. As noted in another response, your question resembles packing problems which are NP-complete. And, of course, your problem is a generalization of the one addressed in this paper, since you are dealing with non-rectangular areas. You could start by breaking your area up into the minimum number of rectangles, another interesting problem in itself. And finally, even if you could do that efficiently, I'm not sure if tiling those rectangles optimally would result in an overall optimal tiling.
As the author notes, a greedy algorithm is a good place to start: just put down the biggest square you can until the area is full.
Packing Problem
Knapsack Problem
And an article on solving 2d packing problem

Resources