Skip to content

Instantly share code, notes, and snippets.

@zeffii
Last active April 28, 2022 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeffii/2ffb911785d78e50a505318cc1497e78 to your computer and use it in GitHub Desktop.
Save zeffii/2ffb911785d78e50a505318cc1497e78 to your computer and use it in GitHub Desktop.
geopandas world to polygons
"""
>in geom s
out verts v
out edges s
out faces s
"""
try:
import mathutils
import pandas as pd
import shapely.geometry as sg
from sverchok.data_structure import get_edge_loop
from sverchok_gis.utils.shapely_parsing import get_edge_loops_from_multipoly
from sverchok_gis.utils.shapely_parsing import get_face_indices_from_multipoly
for geo in geom[0]:
coords = geo.__geo_interface__['coordinates']
indices = []
if isinstance(geo, sg.Polygon):
array_2d = np.array(coords[0])
edge_list = get_edge_loop(array_2d.shape[0])
indices = mathutils.geometry.tessellate_polygon(coords)
elif isinstance(geo, sg.MultiPolygon):
array_2d = np.array(list(pd.core.common.flatten(coords))).reshape((-1, 2))
edge_list = get_edge_loops_from_multipoly(coords)
indices = get_face_indices_from_multipoly(coords)
else:
continue
verts.append(np.c_[ array_2d, np.zeros(array_2d.shape[0])])
edges.append(edge_list)
faces.append(indices)
except Exception as err:
print(err)
# shapely_parsing.py
import mathutils
from sverchok.data_structure import get_edge_loop
def offset(inlist, n):
return [[a+n, b+n] for a, b in inlist]
def get_edge_loops_from_multipoly(coords):
"""
input:
"coords" is a datatype similar to what you get from:
coords = geo.__geo_interface__['coordinates']
output:
a list of edge indices that reference the vertices in coords as if they were a "flat" list of coordinate pairs.
[[x1, y1], [x2, y2], ....]
"""
idx = 0
edge_list = []
for coordset in coords:
for loop in coordset:
N = len(loop)
temp_edge_list = get_edge_loop(N)
if idx > 0:
temp_edge_list = [[a+idx, b+idx] for a, b in temp_edge_list]
idx += N
edge_list.extend(temp_edge_list)
return edge_list
def get_face_indices_from_multipoly(coords):
"""
this is similar to get_edge_loops_from_multipoly, except it tesselates complex ngons and
returns their index lists.
"""
idx = 0
face_list = []
for coordset in coords:
for loop in coordset:
N = len(loop)
temp_face_list = mathutils.geometry.tessellate_polygon([loop])
if idx > 0:
temp_face_list = [[i+idx for i in a] for a in temp_face_list]
idx += N
face_list.extend(temp_face_list)
return face_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment