Find the number of separate polygons given a list of coordinates/points - algorithm

Given a list of coordinates (x, y) that form up polygons is there a specific algorithm/s that can be used to find the number of separate polygons "not colliding polygons" that these points create?
And if there is no algorithm/s what would be the most efficient way to calculate these separate polygons?
I have tried using SAT but the performance is bad, since i have to create each individual polygon and check it for collision against every other polygon.
To illustrate what i want to ultimately achieve, in the following picture you can see the polygons that i'd like to calculate/find which are in some cases comprised of connecting squares.
Also note that i actually start with x, y coordinates for the center of a square and based on a radius i calculate corner points, so i have access to both methods, but mainly opted for the corner points for SAT.
P.S. i'm doing this in lua, but would happily accept any code samples/solutions in other languages.

Fast sweep-line algorithm are described in these papers:
Hiroshi Imai, Takao Asano,
Finding the connected components and a maximum clique of an intersection graph of rectangles in the plane,
Journal of Algorithms 4 (1983) 310—323
H. Edelsbrunner, J. v. Leeuwen, Th. Ottmann and D. Wood,
Computing the connected components of simple rectilinear geometrical objects in d-space,
RAIRO Inform. Theor. 18 (1984) 171—183.

Put all the edges of every polygon in a hash table with the edge as the key (specifically the key will be the two corner points which the edge connects, in sorted order) and the polygon identifier as the value. When adding an edge to the hash-table, just check if an identical edge already exists (same key). This would let you find the duplicate/shared edges.

Related

How to compute the set of polygons from a set of overlapping circles?

This question is an extension on some computation details of this question.
Suppose one has a set of (potentially overlapping) circles, and one wishes to compute the area this set of circles covers. (For simplicity, one can assume some precomputation steps have been made, such as getting rid of circles included entirely in other circles, as well as that the circles induce one connected component.)
One way to do this is mentioned in Ants Aasma's and Timothy's Shields' answers, being that the area of overlapping circles is just a collection of circle slices and polygons, both of which the area is easy to compute.
The trouble I'm encountering however is the computation of these polygons. The nodes of the polygons (consisting of circle centers and "outer" intersection points) are easy enough to compute:
And at first I thought a simple algorithm of picking a random node and visiting neighbors in clockwise order would be sufficient, but this can result in the following "outer" polygon to be constructed, which is not part of the correct polygons.
So I thought of different approaches. A Breadth First Search to compute minimal cycles, but I think the previous counterexample can easily be modified so that this approach results in the "inner" polygon containing the hole (and which is thus not a correct polygon).
I was thinking of maybe running a Las Vegas style algorithm, taking random points and if said point is in an intersection of circles, try to compute the corresponding polygon. If such a polygon exists, remove circle centers and intersection points composing said polygon. Repeat until no circle centers or intersection points remain.
This would avoid ending up computing the "outer" polygon or the "inner" polygon, but would introduce new problems (outside of the potentially high running time) e.g. more than 2 circles intersecting in a single intersection point could remove said intersection point when computing one polygon, but would be necessary still for the next.
Ultimately, my question is: How to compute such polygons?
PS: As a bonus question for after having computed the polygons, how to know which angle to consider when computing the area of some circle slice, between theta and 2PI - theta?
Once we have the points of the polygons in the right order, computing the area is a not too difficult.
The way to achieve that is by exploiting planar duality. See the Wikipedia article on the doubly connected edge list representation for diagrams, but the gist is, given an oriented edge whose right face is inside a polygon, the next oriented edge in that polygon is the reverse direction of the previous oriented edge with the same head in clockwise order.
Hence we've reduced the problem to finding the oriented edges of the polygonal union and determining the correct order with respect to each head. We actually solve the latter problem first. Each intersection of disks gives rise to a quadrilateral. Let's call the centers C and D and the intersections A and B. Assume without loss of generality that the disk centered at C is not smaller than the disk centered at D. The interior angle formed by A→C←B is less than 180 degrees, so the signed area of that triangle is negative if and only if A→C precedes B→C in clockwise order around C, in turn if and only if B→D precedes A→D in clockwise order around D.
Now we determine which edges are actually polygon boundaries. For a particular disk, we have a bunch of angle intervals around its center from before (each sweeping out the clockwise sector from the first endpoint to the second). What we need amounts to a more complicated version of the common interview question of computing the union of segments. The usual sweep line algorithm that increases the cover count whenever it scans an opening endpoint and decreases the cover count whenever it scans a closing endpoint can be made to work here, with the adjustment that we need to initialize the count not to 0 but to the proper cover count of the starting angle.
There's a way to do all of this with no trigonometry, just subtraction and determinants and comparisons.

Can one polygon be transformed into another using only parallel translation and proportional scaling?

At the entrance, two polygons are given (the coordinates of the vertices of these polygons are listed in the order of their traversal; however, the traversal order for different polygon angles can be chosen different). Can one polygon be transformed into another using only parallel translation and proportional scaling?
I have following idea
So, find some common peak for two polygons and make the transfer of one polygon so that these vertices lie on one point then Scaling so that the neighboring point matches the corresponding point of another polygon, but I think it's wrong , at least I can't write it in code
Is there some special formula or theorem for this problem?
I would solve it like this.
Find the necessary parallel transport.
Find the necessary scaling.
See if they are the same polygon now.
So to start take the vertex that it farthest to the left, and if there is a tie, the one that is farthest down. Find that for both polygons. Use parallel transport to put that vertex at the origin for both.
Now take the vertex that is farthest to the right, and if there is a tie, the one that is farthest up. Find that for both polygons. If it is not at the same slope, then they are different. If it is, then scale one so that the points match.
Now see if all of the points match. If not, they are different. Otherwise the answer is yes.
Compute the axis-aligned bounding boxes of the two polygons.
If the aspect ratios do not match, the answer is negative. Otherwise the ratio of corresponding sides is your scaling factor. The translation is obtained by linking the top left corners and the transformation equations are
X = s.(x - xtl) + Xtl
Y = s.(y - ytl) + Ytl
where s is the scaling factor and (xtl, ytl), (Xtl, Ytl) are the corners.
Now choose a vertex of the first polygon, predict the coordinates in the other and find the matching vertex. If you can't, the answer is negative. Otherwise, you can compare the remaining vertices*.
*I assume that the polygons do not have overlapping vertices. If they can have arbitrary self-overlaps, I guess that you have to try matching all vertices, with all cyclic permutations.

How to compute the union polygon of two (or more) rectangles

For example we have two rectangles and they overlap. I want to get the exact range of the union of them. What is a good way to compute this?
These are the two overlapping rectangles. Suppose the cords of vertices are all known:
How can I compute the cords of the vertices of their union polygon? And what if I have more than two rectangles?
There exists a Line Sweep Algorithm to calculate area of union of n rectangles. Refer the link for details of the algorithm.
As said in article, there exist a boolean array implementation in O(N^2) time. Using the right data structure (balanced binary search tree), it can be reduced to O(NlogN) time.
Above algorithm can be extended to determine vertices as well.
Details:
Modify the event handling as follows:
When you add/remove the edge to the active set, note the starting point and ending point of the edge. If any point lies inside the already existing active set, then it doesn't constitute a vertex, otherwise it does.
This way you are able to find all the vertices of resultant polygon.
Note that above method can be extended to general polygon but it is more involved.
For a relatively simple and reliable way, you can work as follows:
sort all abscissas (of the vertical sides) and ordinates (of the horizontal sides) independently, and discard any duplicate.
this establishes mappings between the coordinates and integer indexes.
create a binary image of size NxN, filled with black.
for every rectangle, fill the image in white between the corresponding indexes.
then scan the image to find the corners, by contour tracing, and revert to the original coordinates.
This process isn't efficient as it takes time proportional to N² plus the sum of the (logical) areas of the rectangles, but it can be useful for a moderate amount of rectangles. It easily deals with coincidences.
In the case of two rectangles, there aren't so many different configurations possible and you can precompute all vertex sequences for the possible configuration (a small subset of the 2^9 possible images).
There is no need to explicitly create the image, just associate vertex sequences to the possible permutations of the input X and Y.
Look into binary space partitioning (BSP).
https://en.wikipedia.org/wiki/Binary_space_partitioning
If you had just two rectangles then a bit of hacking could yield some result, but for finding intersections and unions of multiple polygons you'll want to implement BSP.
Chapter 13 of Geometric Tools for Computer Graphics by Schneider and Eberly covers BSP. Be sure to download the errata for the book!
Eberly, one of the co-authors, has a wonderful website with PDFs and code samples for individual topics:
https://www.geometrictools.com/
http://www.geometrictools.com/Books/Books.html
Personally I believe this problem should be solved just as all other geometry problems are solved in engineering programs/languages, meshing.
So first convert your vertices into rectangular grids of fixed size, using for example:
MatLab meshgrid
Then go through all of your grid elements and remove any with duplicate edge elements. Now sum the number of remaining meshes and times it by the area of the mesh you have chosen.

Plotting Distance Constrained Points on a Plane

I'm crossposting this from the mathematics stack exchange at the suggestion of one user who thought somebody here with experience in embedding algorithms might be able to help, though it should be noted that I'm not trying to do a strict graph embedding (which would not allow for vertices to intersect).
Does anybody know of some algorithmic way to tell if it is possible to plot a set of distance constrained points on a cartesian plane. Or, better still, a method to determine the minimum number of dimensions required to accurately depict the points.
As an example: If you have three points and a constraint that says they are all one unit away from each other, you can plot this easily on a cartesian plane as an equilateral triangle.
However, if you have the constraints A->B = 1, A->C = 1, and B->C = 3 then you will not be able to plot these points while maintaining their distances.
However in my case I have a graph with many more than three vertices. The graph is definitely non-planar: one such case involves 1407 vertices all of which are connected by a weighted bidirectional edge that defines the "distance" between the two vertices.
The question is, is there some way to tell if I can depict this graph with accurate distances on a cartesian plane. I know I can't depict it without edges crossing, but I don't care about doing that. I just want the points on the plane an appropriate distance from each other.
Additional information about the graph in case it helps:
1) Each node represents a set of points. 2) The edge weights are derived by optimally overlaying the point sets from each pair of nodes and then taking the RMSD of the resulting point sets. 3) The sets of points represented by any two nodes can be paired with each other. That is, we can think of each node as a set of 8 points numbered 1-8. This numbering is static. When I overlay node A and node B, the points are numbered identically to when I overlay A and C and B and C.
My thoughts: Because RMSD is a metric on R^3 (At least I believe so. This paper claims to prove it http://onlinelibrary.wiley.com/doi/10.1107/S0108767397010325/abstract), it should be possible for me to do this in R^3 at the very least.
As my real goal here is to turn this set of points into a nice figure, a three dimensional depiction would actually suffice, as I could depict the 3D figure in 2D. I also recognize that numerical instability in the particular optimal overlay algorithm I'm using will cause issues, but I'm interested in the answer for an ideal case.

rectilinear polygon intersection

I am looking for / trying to develop an optimal algorithm for rectilinear polygon intersection with rectangles. The polygons I am testing do not have holes.
Answers like those given here and here are for very general polygons, and the solutions are understandably quite complex.
Hoping that the S.O. community can help me document algorithms for the special cases with just rectilinear polygons.
I am looking for the polygon filled in green in the image below:
The book Computational Geometry: an Introduction by Preparata and Shamos has a chapter on rectilinear polygons.
Use a sweep line algorithm, making use of the fact that a rectilinear polygon is defined by its vertices.
Represent the vertices along with the rectangle that they belong to, i.e. something like (x, y, #rect). To this set of points, add those points that result from the intersections of all edges. These new points are of the form (x, y, final), since we already know that they belong to the resulting set of points.
Now:
sort all points by their x-value
use a sweep line, starting at the first x-coordinate; for each new point:
if it's a "start point", add it to a temporary set T. Mark it "final" if it's a point from rectangle A and between y-coordinates from points from rectangle B in T (or vice versa).
if it's an "end point", remove it and its corresponding start point from T.
After that, all points that are marked "final" denote the vertices of the resulting polygon.
Let N be the total number of points. Further assuming that testing whether we should mark a point as being "final" takes time O(log(n)) by looking up T, this whole algorithm is in O(N*log(N)).
Note that the task of finding all intersections can be incorporated into the above algorithm, since finding all intersections efficiently is itself a sweep line algorithm usually. Also note that the resulting set of points may contain more than one polygon, which makes it slightly harder to reconstruct the solution polygons out of the "final" vertices.

Resources