a set of utility functions for manipulating shapely.geometry
objects
Colab Notebook
a set of utility functions for manipulating shapely.geometry
objects
Colab Notebook
# -*- encoding: utf-8 -*- | |
""" | |
Codes for Manipulating Geometric Objects | |
A geometric object can be anything that is defined by | |
`shapely.geometry` class or read from shapefile using | |
`geopandas`. This code can be used to manipulate | |
these files for better control and requirement. | |
@author : Debmalya Pramanik | |
""" | |
from shapely.geometry import ( | |
Polygon, | |
MultiPolygon | |
) | |
def flatten(geometry : MultiPolygon) -> MultiPolygon: | |
""" | |
Flatten a Higher-Order Multi-Polygon to a Second Order Polygon | |
A higher order `Polygon` or `MultiPloygon` is often represented with | |
`Z` symbol when parsed with `geopandas`. This type of frame is also | |
vulnerable to `shapely` reading file error. The functions aims to | |
flatten any higher dimensional data to only its `xy` form be simply | |
considering first two dimensional values. For example: | |
.. math: | |
MultiPolygon Z(((1, 2, 3), (4, 5, 6)), ((1, 2, 3), (4, 5, 6))) > MultiPolygon(((1, 2), (4, 5)), ((1, 2), (4, 5))) | |
As explained, all higher order terms are simply neglected forcefully using `xyz[:2]` | |
comprehensions. | |
""" | |
flattened = [] | |
for pt in geometry: | |
# consider all has `z` | |
# TODO raise error/catch when not met | |
# also, implemented only for `MultiPolygon` | |
if pt.geom_type == "Polygon": | |
polys = [xyz[:2] for xyz in list(pt.exterior.coords)] | |
flattened.append(Polygon(polys)) | |
elif pt.geom_type == "MultiPolygon": | |
inner_multi_poly = [] | |
for ap in pt: | |
# loop through inner multi-poly | |
# discard any higher dimensional values | |
polys = [xyz[:2] for xyz in list(ap.exterior.coords)] | |
inner_multi_poly.append(Polygon(polys)) | |
flattened.append(MultiPolygon(inner_multi_poly)) | |
else: | |
raise ValueError(f"{pt.geom_type} is not yet implemented.") | |
return MultiPolygon(flattened) |