开发-计算几何常见操作
计算几何常用的库
- shapely
- geopandas
- pygeos
常见的代码
# 系统/文件
import os
from collections import defaultdict
import heapq
import math
# 基础
import numpy as np
import pandas as pd
import ezdxf
import heapdict
# 计算几何相关的库
import pygeos
import shapely
from shapely import wkt
from shapely.geometry import Polygon, Point, LineString
from shapely.ops import split, nearest_points, unary_union, triangulate, voronoi_diagram, cascaded_union, linemerge
import geopandas as gpd
# 画图相关
from matplotlib import pyplot as plt
import seaborn as sn
# 网络相关
from tqdm import tqdm
import networkx as nx
# 警告
import warnings
warnings.filterwarnings('ignore')
# 1.使用缓冲区,减少不相交线
road_buffer_list = [road.buffer(5, cap_style=1, resolution=10) for road in road_linestring]
# 2.合并,获得并集
union_road = unary_union(road_buffer_list)
# 3.三角剖分
tri_network = triangulate(union_road)
center_line_tup = [(str(center_line.coords[0]), str(center_line.coords[-1])) for center_line in ls]
se_points = set([item for tup in center_line_tup for item in tup])
point_index = dict(zip(se_points, range(len(se_points))))
edges = pd.DataFrame([
{'source': str(point_index[str(line.coords[0])]),
'target': str(point_index[str(line.coords[-1])]),
'edgeId': idx,
'weight': line.length,
'geo': str(line)}
for idx, line in enumerate(ls)
])
edges.to_csv('a.csv', index=None)
g = nx.from_pandas_edgelist(edges, 'source', 'target', edge_attr=['weight'])
path = nx.shortest_path(g, source='34', target='48')
df1 = edges[(edges['source'].isin(path)) & (edges['target'].isin(path))]
df1.to_csv('path.csv', index=None)
# conda install --channel conda-forge geopandas
# https://stackoverflow.com/questions/61122875/geopandas-how-to-read-a-csv-and-convert-to-a-geopandas-dataframe-with-polygons
gdf = gpd.GeoDataFrame.from_file('./datasets/edges.csv')
gdf['geometry'] = gdf['geo'].apply(wkt.loads)
gdf = gpd.GeoDataFrame(gdf, crs='epsg:4326')
# https://stackoverflow.com/questions/68383793/geopandas-plot-is-streched
fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(30, 15))
gdf.plot(ax=ax1)
gdf.plot(ax=ax2)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
fig.savefig('out.png', dpi=100)