# conda install geopandas
Dfsu - Export to shapefile
- Read selected item and timestep from dfsu
- Extract geometry
- Create GeoPandas dataframe
- Save to ESRI shapefile
import numpy as np
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import mikeio
Step 1. read the selected data
= mikeio.read("../tests/testdata/wind_north_sea.dfsu")
ds = ds["Wind speed"][0]
ws ; ws.plot()
Step 2. extract geometry
= ds.geometry.to_shapely()
shp type(shp)
shapely.geometry.multipolygon.MultiPolygon
Geopandas does not like multipolygon, it should be a list of polygons
= [p for p in shp.geoms] poly_list
Step 3. Create a geopandas dataframe
= pd.DataFrame({'wind_speed':ws.to_numpy()})
df df.head()
wind_speed | |
---|---|
0 | 9.530760 |
1 | 9.652719 |
2 | 9.806072 |
3 | 8.775489 |
4 | 11.013206 |
= gpd.GeoDataFrame(df,geometry=poly_list) gdf
Step 4. Save to shapefile
"wind_speed.shp") gdf.to_file(
Step 5…
Do further work in QGIS
Would you prefer to have this workflow to be a method on the mikeio.Dfsu
class?
Post an issue on GitHub !
Contour lines
# get coordinates
= ds.geometry.element_coordinates
ec = ec[:,0]
lon = ec[:,1] lat
# Select item and timestep
= ds.Wind_speed[0].to_numpy() m
# Interpolate to cartesian grid
from scipy.interpolate import griddata
= 200, 200
numcols, numrows = np.linspace(lon.min(), lon.max(), numcols)
xi = np.linspace(lat.min(), lat.max(), numrows)
yi = np.meshgrid(xi, yi)
xi, yi
= griddata(points=ec[:,0:2],values=m,xi=(xi,yi),method='cubic') grid_z
=np.arange(4, 14, 0.5)
contour_levels= plt.contour(xi,yi,grid_z,levels=contour_levels) cn
from shapely.geometry import LineString
= []
poly_list
for i in range(len(cn.collections)):
= cn.collections[i].get_paths()[0]
p = p.vertices
v = v[:,0]
x = v[:,1]
y = LineString([(i[0], i[1]) for i in zip(x,y)])
poly if(poly.is_empty):
print(f"{i} is empty")
poly_list.append(poly)
# Clip to domain
= ds.geometry.to_shapely().buffer(0)
domain = [p.intersection(domain) for p in poly_list] poly_list
# Create GeoDataframe
= pd.DataFrame({'wind_speed':contour_levels})
df = gpd.GeoDataFrame(df,geometry=poly_list)
gdf gdf.head()
wind_speed | geometry | |
---|---|---|
0 | 4.0 | LINESTRING EMPTY |
1 | 4.5 | LINESTRING EMPTY |
2 | 5.0 | LINESTRING (0.74084 49.95996, 0.79247 49.94723... |
3 | 5.5 | LINESTRING (0.74084 50.00444, 0.79247 49.99547... |
4 | 6.0 | LINESTRING (0.68920 50.08850, 0.73941 50.06993... |
# export shapefile
"wind_speed_contours.shp") gdf.to_file(
Clean up
import os
= ["wind_speed","wind_speed_contours"]
files
= ["cpg","dbf","shp","shx"]
exts
for file in files:
for ext in exts:
= f"{file}.{ext}"
filename if os.path.exists(filename): os.remove(filename)