Skip to content

Instantly share code, notes, and snippets.

@ZenithClown
Last active April 18, 2023 17:53
Show Gist options
  • Save ZenithClown/83cb9fdcc95a7d9bc29851189e0219ea to your computer and use it in GitHub Desktop.
Save ZenithClown/83cb9fdcc95a7d9bc29851189e0219ea to your computer and use it in GitHub Desktop.
Codes for Manipulating Geometric Objects

Geometric Objects

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment