'Cut a shapely polygon into N equally sized polygons

I have a Shapely polygon. I want to cut these polygon into n polygons, which all have more-or-less equally sized areas. Equally sized would be best, but an approximation would be okay too.

I have tried to use the two methods described here, which both are a step in the right direction by not what I need. Both don't allow for a target n

I looked into voronoi, with which I am largely unfamiliar. The resulting shapes this analysis gives would be ideal, but it requires points, not a shape as input.



Solution 1:[1]

Another out-of-the-box option out there is the h3 polyfill function. Basically any repeating structure would work (triangle, square, hex), but Uber's library uses hexes so you're stuck with that unless you write a module to do the same thing with one of the other shapes. You still have the issue with "n" not being specified directly though (only indirectly through the discrete zoom level options).

polyfill

Solution 2:[2]

Just combining the response and basic polyfill docs provided by @user3496060 (very helpful for me, thank you), here's a simple function.

And here's a great notebook from the h3 repo. Check out the "Census Polygon to Hex" section for how they use polyfill().

    def h3_fill_shapely_poly(poly = shape, res = 10):
        """
        inputs:
               - poly: must be a shapely Polygon, cannot be any other shapely object
               - res: resolution (higher means more specific zoom)
        output:
               - h3_fill: a Python set() object, generated by polypill
        """
        coordinates = [[i[0], i[1]] for i in poly.exterior.coords]
        geo_json = {
                "type": "Polygon",
                "coordinates": [coordinates]
        }
        h3_fill = h3.polyfill(geo_json, res, geo_json_conformant=False)
        print(f'h3_fill =\n{type(h3_fill), h3_fill}')
        return h3_fill

Solution 3:[3]

You either need to escape the inner single quotes or use double quotes for the query string.

if ($result = mysqli_query($conn,'SELECT * FROM temptable
     where postcode<>\'\'
     ORDER BY ' .  $column . ' ' . $sort_order)) {

or

if ($result = mysqli_query($conn,"SELECT * FROM temptable
     where postcode <> ''
     ORDER BY $column $sort_order")) {

Make sure you are validating the values being passed in for $column and $sort_order, otherwise this will be a very simple SQL injection attack vulnerability. Better still, look into using prepared statements when building SQL queries which concatenate strings based on user input.

Prepared Statements

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 nnichols