首次提交

This commit is contained in:
2026-10-10 21:56:35 +08:00
commit 246d9b7870
96 changed files with 7109 additions and 0 deletions
@@ -0,0 +1,215 @@
# 二维网格基础
本教程介绍 `meshkernel` 库的基本用法。
`meshkernel` 可以创建和操作多种网格。
最常见的应用涉及二维非结构网格,因此本教程重点介绍这类网格。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
首先导入所需的库。
```python
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import GeometryList, MakeGridParameters, MeshKernel, ProjectionType
```
`meshkernel` 提供了一组便捷方法,用于创建常见网格。
这里使用 `curvilinear_compute_rectangular_grid` 方法创建一个简单的曲线网格。该方法的完整参数请参阅相应文档。
```python
mk = MeshKernel()
make_grid_parameters = MakeGridParameters()
make_grid_parameters.num_columns = 3
make_grid_parameters.num_rows = 2
make_grid_parameters.angle = 0.0
make_grid_parameters.origin_x = 0.0
make_grid_parameters.origin_y = 0.0
make_grid_parameters.block_size_x = 1.0
make_grid_parameters.block_size_y = 1.0
mk.curvilinear_compute_rectangular_grid(make_grid_parameters)
```
将曲线网格转换为非结构网格,并获取生成的 `mesh2d`。
```python
mk.curvilinear_convert_to_mesh2d()
```
```python
mesh2d_input = mk.mesh2d_get()
```
`Mesh2D` 有三个必需属性,仅凭它们就可以完整描述任意非结构网格。
前两个属性是 `node_x` 和 `node_y`,它们是一维 `double` 数组,用来描述节点的位置,如下图所示。
```python
fig, ax = plt.subplots()
# 绘制白色点,仅用于调整图的显示范围
ax.plot(mesh2d_input.node_x, mesh2d_input.node_y, "ow")
# 为节点编号
for i in range(mesh2d_input.node_x.size):
ax.annotate(
int(i),
xy=(mesh2d_input.node_x[i], mesh2d_input.node_y[i]),
ha="center",
va="center",
fontsize=12,
color="blue",
)
```
![单元格 9 的绘图输出](images/01_mesh2d_basics_9_0.png)
第三个必需属性是 `edge_nodes`,它描述组成各条边的节点索引。
每两个索引表示一条边。因此,在本例中,0–4、1–5、2–6 等索引对分别表示一条边。
```python
mesh2d_input.edge_nodes
```
```text
array([ 0, 4, 1, 5, 2, 6, 3, 7, 4, 8, 5, 9, 6, 10, 7, 11, 0,
1, 1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 9, 10, 10, 11],
dtype=int32)
```
结合这三个参数即可绘制网格。
```python
fig, ax = plt.subplots()
mesh2d_input.plot_edges(ax, color="blue")
```
![单元格 13 的绘图输出](images/01_mesh2d_basics_13_0.png)
要与 `meshkernel` 库交互,首先创建一个 `MeshKernel` 类实例。
构造函数的 `projection` 参数用于指定网格采用笛卡尔坐标(`ProjectionType.CARTESIAN`)还是球面坐标(`ProjectionType.SPHERICAL`)。
```python
mk = MeshKernel(projection=ProjectionType.CARTESIAN)
```
每个实例都维护各自的状态,可以通过对应的获取和设置方法访问这些状态。
```python
mk.mesh2d_set(mesh2d_input)
```
```python
mesh2d_output_0 = mk.mesh2d_get()
```
刚才设置了 `mesh2d`,随后立即将它取出,期间没有要求 `meshkernel` 执行其他操作。
设置 `mesh2d` 后,`meshkernel` 已计算出网格面数据和边的坐标。
```python
fig, ax = plt.subplots()
mesh2d_output_0.plot_faces(ax)
# 在网格面中心标注面索引
for face_index, (face_x, face_y) in enumerate(
zip(mesh2d_output_0.face_x, mesh2d_output_0.face_y)
):
ax.text(face_x, face_y, face_index, ha="center", va="center", fontsize=22)
```
![单元格 20 的绘图输出](images/01_mesh2d_basics_20_0.png)
`meshkernel` 还会查找边的中点,并将其作为属性添加到 `Mesh2D` 类中。
```python
fig, ax = plt.subplots()
ax.plot(mesh2d_output_0.edge_x, mesh2d_output_0.edge_y, ".");
```
![单元格 22 的绘图输出](images/01_mesh2d_basics_22_0.png)
目前网格看起来仍然是结构化的。接下来添加几个节点,改变它的结构。
```python
node_index_0 = mk.mesh2d_insert_node(4.0, 1.5)
node_index_1 = mk.mesh2d_insert_node(4.0, 2.5)
```
还需要将新增节点连接起来,否则 `meshkernel` 会将未连接的节点清理掉。
```python
edge_index_0 = mk.mesh2d_insert_edge(7, node_index_0)
edge_index_1 = mk.mesh2d_insert_edge(node_index_0, node_index_1)
edge_index_3 = mk.mesh2d_insert_edge(node_index_1, 11)
```
获取更新后的状态。
```python
mesh2d_output_1 = mk.mesh2d_get()
```
绘制输出网格,可以看到 `meshkernel` 已立即识别出一个新的网格面。
```python
fig, ax = plt.subplots()
mesh2d_output_1.plot_faces(ax)
# 在网格面中心标注面索引
for face_index, (face_x, face_y) in enumerate(
zip(mesh2d_output_1.face_x, mesh2d_output_1.face_y)
):
ax.text(face_x, face_y, face_index, ha="center", va="center", fontsize=22)
```
![单元格 30 的绘图输出](images/01_mesh2d_basics_30_0.png)
也可以删除节点。
```python
mk.mesh2d_delete_node(node_index_1)
mesh2d_output_2 = mk.mesh2d_get()
```
网格重新变成六个面,但仍留有一条悬挂边。
```python
fig, ax = plt.subplots()
mesh2d_output_2.plot_edges(ax, color="blue")
```
![单元格 34 的绘图输出](images/01_mesh2d_basics_34_0.png)
悬挂边通常是不需要的,因此 `meshkernel` 提供了处理它们的方法。首先,可以统计悬挂边的数量。
```python
hanging_edges = mk.mesh2d_get_hanging_edges()
assert hanging_edges.size == 1
```
`meshkernel` 还可以查找并删除悬挂边。
```python
mk.mesh2d_delete_hanging_edges()
mesh2d_output_3 = mk.mesh2d_get()
```
删除悬挂边后,网格恢复到最初的状态。
```python
fig, ax = plt.subplots()
mesh2d_output_3.plot_edges(ax, color="blue")
```
![单元格 40 的绘图输出](images/01_mesh2d_basics_40_0.png)
@@ -0,0 +1,121 @@
# 一维网格基础
本教程介绍一维网格的处理方式,以及一维网格与二维网格之间的交互。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
首先导入所需的库。
```python
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import Mesh1d, GeometryList, MakeGridParameters, MeshKernel
```
首先,使用正弦函数上的八个点描述一维网格。原说明写为六个点,此处按下方 `np.linspace(..., 8)` 代码修正。
```python
node_x = np.linspace(0, 2 * np.pi, 8)
node_y = np.sin(node_x)
```
为了形成一条连续的折线,将每个点与下一个点相连。
```python
edge_nodes = np.zeros(node_x.size * 2, np.int32)
edge_index = 0
for node_index in range(node_x.size - 1):
edge_nodes[edge_index] = node_index
edge_index += 1
edge_nodes[edge_index] = node_index + 1
edge_index += 1
```
然后创建 `Mesh1d` 实例。
```python
mesh1d_input = Mesh1d(node_x, node_y, edge_nodes)
```
创建 `MeshKernel` 实例。
```python
mk = MeshKernel()
```
使用 `curvilinear_compute_rectangular_grid` 方法创建一个简单的曲线网格。该方法的完整参数请参阅相应文档。
```python
make_grid_parameters = MakeGridParameters()
make_grid_parameters.num_columns = 7
make_grid_parameters.num_rows = 3
make_grid_parameters.angle = 0.0
make_grid_parameters.origin_x = -0.1
make_grid_parameters.origin_y = -1.5
make_grid_parameters.block_size_x = 1.0
make_grid_parameters.block_size_y = 1.0
mk.curvilinear_compute_rectangular_grid(make_grid_parameters)
```
将曲线网格转换为非结构 `mesh2d`,并从 `MeshKernel` 中获取该网格。
```python
mk.curvilinear_convert_to_mesh2d()
mesh2d_input = mk.mesh2d_get()
```
设置 `mesh1d`。
```python
mk.mesh1d_set(mesh1d_input)
```
当前网格如下图所示:
```python
fig, ax = plt.subplots()
mesh1d_input.plot_edges(ax, color="blue")
mesh2d_input.plot_edges(ax, color="black")
```
![单元格 18 的绘图输出](images/02_mesh1d_basics_18_0.png)
同时使用一维和二维网格时,通常需要在它们之间建立连接(contacts)。
所有连接计算方法都需要节点掩码,用于确定哪些一维节点应参与连接。
本例考虑所有节点。
```python
node_mask = np.full(mesh1d_input.node_x.size, True)
```
调用 `contacts_compute_multiple` 方法建立连接。
```python
mk.contacts_compute_multiple(node_mask)
```
然后从 `MeshKernel` 实例中获取状态。
```python
mesh1d_output_0 = mk.mesh1d_get()
mesh2d_output_0 = mk.mesh2d_get()
contacts_output_0 = mk.contacts_get()
```
可以看到,一维节点与二维网格面之间已经建立了连接。
```python
fig, ax = plt.subplots()
mesh1d_output_0.plot_edges(ax, color="blue")
mesh2d_output_0.plot_edges(ax, color="black")
contacts_output_0.plot_edges(ax, mesh1d_output_0, mesh2d_output_0, color="red")
```
![单元格 26 的绘图输出](images/02_mesh1d_basics_26_0.png)
@@ -0,0 +1,71 @@
# 在给定几何区域内生成简单三角网格
本教程介绍如何在给定几何区域内生成二维网格。
首先导入所需的库。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
```python
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import GeometryList, MeshKernel
```
首先,使用 NumPy 从 Deltares 自定义多边形文件 `test.pol` 中加载数据。
注意,需要忽略文件开头的若干行,以跳过 Deltares 特有的头部数据。
```python
polygon_file_path = Path().absolute() / "data_examples" / "test.pol"
polygon_np = np.loadtxt(polygon_file_path, comments="*", skiprows=8, dtype=np.double)
```
提取从文件中加载的数据,并按照 `MeshKernel` 的要求,将其存入 `GeometryList`。
```python
x_coordinates = np.array(polygon_np[:, 0], dtype=np.double)
y_coordinates = np.array(polygon_np[:, 1], dtype=np.double)
polygon = GeometryList(x_coordinates, y_coordinates)
```
导入的多边形如下图所示:
```python
fig, ax = plt.subplots()
ax.plot(x_coordinates, y_coordinates, ".-", color="green");
```
![单元格 7 的绘图输出](images/03_tri_mesh2d_pol_7_0.png)
接着创建一个 `MeshKernel` 实例。
```python
mk = MeshKernel()
```
现在可以调用 `MeshKernel` 的 `mesh2d_make_triangular_mesh_from_polygon` 方法,根据给定多边形生成三角网格。
```python
mk.mesh2d_make_triangular_mesh_from_polygon(polygon)
```
然后从 `MeshKernel` 实例中获取状态。
```python
mesh2d_output_0 = mk.mesh2d_get()
```
绘制生成的网格。
```python
fig, ax = plt.subplots()
mesh2d_output_0.plot_edges(ax, color="black")
```
![单元格 15 的绘图输出](images/03_tri_mesh2d_pol_15_0.png)
@@ -0,0 +1,585 @@
# 曲线网格基础
本教程介绍如何使用 `meshkernel` 库生成曲线网格。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
首先导入所需的库。
```python
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import (
CurvilinearParameters,
MakeGridParameters,
GeometryList,
MeshKernel,
SplinesToCurvilinearParameters,
OrthogonalizationParameters,
)
```
定义一个函数,使用 `curvilinear_compute_transfinite_from_splines` 生成曲线网格,并创建包含该网格的 `MeshKernel` 实例:
- 首先创建用于生成曲线网格的样条曲线,各条样条曲线用 `-999.0` 分隔。
- 在新的 `CurvilinearParameters` 实例中设置 m、n 方向的划分数。
- 创建一个新的 `MeshKernel` 实例。
- 使用超限插值算法生成曲线网格。
```python
def create_mk_instance_with_curvilinear_grid_from_transfinite_method():
r"""创建包含曲线网格的 MeshKernel 实例。"""
mk = MeshKernel()
separator = -999.0
splines_x = np.array(
[
2.0,
4.0,
7.0,
separator,
-1.0,
1.0,
5.0,
separator,
3.0,
-2.0,
separator,
7.0,
4.0,
],
dtype=np.double,
)
splines_y = np.array(
[
1.0,
3.0,
4.0,
separator,
4.0,
6.0,
7.0,
separator,
1.0,
6.0,
separator,
3.0,
8.0,
],
dtype=np.double,
)
splines = GeometryList(splines_x, splines_y)
curvilinear_parameters = CurvilinearParameters()
curvilinear_parameters.n_refinement = 10
curvilinear_parameters.m_refinement = 10
mk.curvilinear_compute_transfinite_from_splines(splines, curvilinear_parameters)
return mk
```
定义一个用于创建矩形曲线网格的函数。
```python
def create_mk_instance_with_a_rectangular_curvilinear_grid(num_columns=3, num_rows=3):
r"""创建包含矩形曲线网格的 MeshKernel 实例的局部函数。"""
mk = MeshKernel()
# 创建 MakeGridParameters 实例并设置参数值
make_grid_parameters = MakeGridParameters()
make_grid_parameters.num_columns = num_columns
make_grid_parameters.num_rows = num_rows
make_grid_parameters.angle = 0.0
make_grid_parameters.origin_x = 0.0
make_grid_parameters.origin_y = 0.0
make_grid_parameters.block_size_x = 10.0
make_grid_parameters.block_size_y = 10.0
mk.curvilinear_compute_rectangular_grid(make_grid_parameters)
return mk
```
## 使用超限插值法生成曲线网格
```python
curvilinear_grid_transfinite = (
create_mk_instance_with_curvilinear_grid_from_transfinite_method().curvilineargrid_get()
)
```
绘制结果。
```python
fig, ax = plt.subplots()
curvilinear_grid_transfinite.plot_edges(ax)
```
![单元格 10 的绘图输出](images/04_curvilineargrid_basics_10_0.png)
## 使用推进前沿法生成曲线网格
定义生成曲线网格的过程,使用 `curvilinear_compute_orthogonal_from_splines` 方法创建包含网格的 `MeshKernel` 实例:
- 首先创建用于生成曲线网格的样条曲线,各条样条曲线用 `-999.0` 分隔。
- 在新的 `CurvilinearParameters` 实例中设置 m、n 方向的划分数。
- 该算法还需要设置从样条曲线生成曲线网格所需的附加参数。
- 然后使用推进前沿算法生成曲线网格。
```python
mk = MeshKernel()
separator = -999.0
splines_x = np.array([-1.0, 2.0, 6.0, separator, 3.0, -2.0, separator], dtype=np.double)
splines_y = np.array([2.0, 5.0, 6.0, separator, 1.0, 6.0, separator], dtype=np.double)
splines_values = np.zeros_like(splines_x)
splines = GeometryList(splines_x, splines_y, splines_values)
curvilinearParameters = CurvilinearParameters()
curvilinearParameters.n_refinement = 10
curvilinearParameters.m_refinement = 10
splinesToCurvilinearParameters = SplinesToCurvilinearParameters()
splinesToCurvilinearParameters.aspect_ratio = 1.0
splinesToCurvilinearParameters.aspect_ratio_grow_factor = 1.0
splinesToCurvilinearParameters.average_width = 0.2
splinesToCurvilinearParameters.nodes_on_top_of_each_other_tolerance = 1e-4
splinesToCurvilinearParameters.min_cosine_crossing_angles = 0.95
splinesToCurvilinearParameters.check_front_collisions = 0
splinesToCurvilinearParameters.curvature_adapted_grid_spacing = 1
splinesToCurvilinearParameters.remove_skinny_triangles = 1
mk.curvilinear_compute_orthogonal_from_splines(
splines, curvilinearParameters, splinesToCurvilinearParameters
)
curvilinear_grid_orthogonal = mk.curvilineargrid_get()
```
绘制结果。
```python
fig, ax = plt.subplots()
curvilinear_grid_orthogonal.plot_edges(ax)
```
![单元格 15 的绘图输出](images/04_curvilineargrid_basics_15_0.png)
## 曲线网格加密与粗化
加密前的网格。
```python
mk = create_mk_instance_with_curvilinear_grid_from_transfinite_method()
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 18 的绘图输出](images/04_curvilineargrid_basics_18_0.png)
在两个选定点之间,为每一行添加两条水平网格线进行加密,并绘制结果。
```python
mk.curvilinear_refine(2.299, 4.612, 3.074, 3.684, 2)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 20 的绘图输出](images/04_curvilineargrid_basics_20_0.png)
删除相同行中的网格线,进行粗化。
```python
mk.curvilinear_refine(2.299, 4.612, 3.074, 3.684, -2)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 22 的绘图输出](images/04_curvilineargrid_basics_22_0.png)
## 创建矩形网格
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid()
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 24 的绘图输出](images/04_curvilineargrid_basics_24_0.png)
也可以根据多边形生成矩形网格。多边形必须闭合。
```python
node_x = np.array([2.5, 5.5, 3.5, 0.5, 2.5], dtype=np.double)
node_y = np.array([0.5, 3.0, 5.0, 2.5, 0.5], dtype=np.double)
geometry_list = GeometryList(node_x, node_y)
```
```python
make_grid_parameters = MakeGridParameters()
make_grid_parameters.num_columns = 10
make_grid_parameters.num_rows = 10
make_grid_parameters.angle = 0.0
make_grid_parameters.origin_x = 0.0
make_grid_parameters.origin_y = 0.0
make_grid_parameters.block_size_x = 0.2
make_grid_parameters.block_size_y = 0.2
```
```python
mk.curvilinear_compute_rectangular_grid_from_polygon(
make_grid_parameters, geometry_list
)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 28 的绘图输出](images/04_curvilineargrid_basics_28_0.png)
## 利用多边形边界上的节点生成曲线网格
定义多边形并生成曲线网格。
```python
node_x = np.array([2, 4, 6, 7, 8, 8, 8, 8, 7, 5, 3, 2, 2, 2, 2], dtype=np.double)
node_y = np.array([1, 1, 1, 1, 1, 1.2, 4, 6, 6, 6, 6, 6, 5, 3, 1], dtype=np.double)
geometry_list = GeometryList(node_x, node_y)
mk = MeshKernel()
mk.curvilinear_compute_transfinite_from_polygon(geometry_list, 0, 4, 7, False)
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 32 的绘图输出](images/04_curvilineargrid_basics_32_0.png)
## 曲线网格正交化
移动一个节点,使网格不再正交,并绘制结果。
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid()
mk.curvilinear_move_node(10.0, 20.0, 18.0, 12.0)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 35 的绘图输出](images/04_curvilineargrid_basics_35_0.png)
执行正交化。
```python
# 在正交化前检查节点位置
orthogonalization_parameters = OrthogonalizationParameters()
orthogonalization_parameters.outer_iterations = 1
orthogonalization_parameters.boundary_iterations = 25
orthogonalization_parameters.inner_iterations = 25
orthogonalization_parameters.orthogonalization_to_smoothing_factor = 0.95
# 初始化曲线网格正交化算法
# 设置要正交化的网格块(本例指定网格的左下角和右上角)
mk.curvilinear_orthogonalize(orthogonalization_parameters, 0.0, 0.0, 30.0, 30.0)
```
绘制正交化后的结果。
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 39 的绘图输出](images/04_curvilineargrid_basics_39_0.png)
## 固定一条网格线进行曲线网格正交化
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid()
mk.curvilinear_move_node(10.0, 20.0, 18.0, 12.0)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 41 的绘图输出](images/04_curvilineargrid_basics_41_0.png)
执行正交化,同时固定被移动节点所在的垂直网格线。
```python
# 在正交化前检查节点位置
orthogonalization_parameters = OrthogonalizationParameters()
orthogonalization_parameters.outer_iterations = 1
orthogonalization_parameters.boundary_iterations = 25
orthogonalization_parameters.inner_iterations = 25
orthogonalization_parameters.orthogonalization_to_smoothing_factor = 0.95
# 固定被移动节点所在的垂直网格线
mk.curvilinear_frozen_line_add(10.0, 0.0, 10.0, 30.0)
# 执行正交化
# 初始化曲线网格正交化算法
# 设置要正交化的网格块(本例指定网格的左下角和右上角)
mk.curvilinear_orthogonalize(orthogonalization_parameters, 0.0, 0.0, 30.0, 30.0)
```
绘制正交化后的结果。
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 45 的绘图输出](images/04_curvilineargrid_basics_45_0.png)
## 曲线网格平滑
移动一个节点,使网格不再平滑,并绘制结果。
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid()
mk.curvilinear_move_node(10.0, 20.0, 18.0, 12.0)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 48 的绘图输出](images/04_curvilineargrid_basics_48_0.png)
执行平滑。
```python
mk.curvilinear_smoothing(10, 0.0, 0.0, 30.0, 30.0)
```
绘制平滑后的结果。
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 52 的绘图输出](images/04_curvilineargrid_basics_52_0.png)
## 曲线网格定向平滑
移动一个节点,使网格不再平滑,并绘制结果。
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid()
mk.curvilinear_move_node(10.0, 20.0, 18.0, 12.0)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 55 的绘图输出](images/04_curvilineargrid_basics_55_0.png)
执行定向平滑。
```python
mk.curvilinear_smoothing_directional(
10, # 平滑迭代次数
10.0,
0.0,
10.0,
30.0, # 用于定义平滑方向的网格线坐标
0.0,
0.0,
30.0,
30.0,
) # 要平滑的网格块角点
```
绘制定向平滑后的结果。
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 59 的绘图输出](images/04_curvilineargrid_basics_59_0.png)
## 曲线网格线平移
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid(5, 5)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 61 的绘图输出](images/04_curvilineargrid_basics_61_0.png)
初始化网格线平移操作,并设置要移动的网格线。
```python
mk.curvilinear_initialize_line_shift()
mk.curvilinear_set_line_line_shift(0.0, 0.0, 0.0, 50.0)
```
设置用于分配网格线位移的网格块。
```python
mk.curvilinear_set_block_line_shift(0.0, 0.0, 20.0, 50.0)
```
将曲线网格左侧的所有节点向左移动。
```python
mk.curvilinear_move_node_line_shift(0.0, 0.0, -50.0, 0.0)
mk.curvilinear_move_node_line_shift(0.0, 10.0, -50.0, 10.0)
mk.curvilinear_move_node_line_shift(0.0, 20.0, -50.0, 20.0)
mk.curvilinear_move_node_line_shift(0.0, 30.0, -50.0, 30.0)
mk.curvilinear_move_node_line_shift(0.0, 40.0, -50.0, 40.0)
mk.curvilinear_move_node_line_shift(0.0, 50.0, -50.0, 50.0)
```
执行网格线平移。前面指定网格块以外的节点不会移动。
```python
mk.curvilinear_line_shift()
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 70 的绘图输出](images/04_curvilineargrid_basics_70_0.png)
## 在曲线网格中插入网格面
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid(5, 5)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 72 的绘图输出](images/04_curvilineargrid_basics_72_0.png)
插入两个网格面。
```python
mk.curvilinear_insert_face(-10.0, 5.0)
mk.curvilinear_insert_face(-5.0, 10.0)
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 75 的绘图输出](images/04_curvilineargrid_basics_75_0.png)
## 删除曲线网格节点
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid(5, 5)
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 77 的绘图输出](images/04_curvilineargrid_basics_77_0.png)
删除角点节点。
```python
mk.curvilinear_delete_node(0.0, 0.0)
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 80 的绘图输出](images/04_curvilineargrid_basics_80_0.png)
## 曲线网格线吸引与排斥
将网格块内的节点向指定网格线吸引。
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid(5, 5)
mk.curvilinear_line_attraction_repulsion(
1.0, # 正值表示排斥网格线,此处为列宽的 1 倍
30.0,
0.0,
30.0,
50.0, # 网格线坐标
10.0,
0.0,
50.0,
50.0,
) # 受影响的网格块
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 84 的绘图输出](images/04_curvilineargrid_basics_84_0.png)
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid(5, 5)
mk.curvilinear_line_attraction_repulsion(
-1.0, # 负值表示吸引网格线,此处为列宽的 0.5 倍
30.0,
0.0,
30.0,
50.0, # 网格线坐标
10.0,
0.0,
50.0,
50.0,
) # 受影响的网格块
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 86 的绘图输出](images/04_curvilineargrid_basics_86_0.png)
## 曲线网格线镜像扩展
以两倍列宽对左侧网格线进行镜像扩展。
```python
mk = create_mk_instance_with_a_rectangular_curvilinear_grid(5, 5)
# 镜像系数、要镜像的网格线数量以及目标网格线
mk.curvilinear_line_mirror(2.0, 1, 0.0, 0.0, 0.0, 50.0)
```
```python
curvilinear_grid = mk.curvilineargrid_get()
fig, ax = plt.subplots()
curvilinear_grid.plot_edges(ax)
```
![单元格 90 的绘图输出](images/04_curvilineargrid_basics_90_0.png)
@@ -0,0 +1,140 @@
# 基于规则网格采样数据的二维网格加密
本教程简要介绍如何使用规则网格采样数据进行网格加密。加密时,通过双线性插值计算网格节点处的水深值。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
首先导入所需的库。
```python
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import (
GeometryList,
GriddedSamples,
MakeGridParameters,
MeshKernel,
MeshRefinementParameters,
RefinementType,
)
```
`meshkernel` 提供了一组便捷方法,用于创建常见网格。
这里使用 `curvilinear_compute_rectangular_grid` 方法创建一个简单的曲线网格。该方法的完整参数请参阅相应文档。
```python
mk = MeshKernel()
make_grid_parameters = MakeGridParameters()
make_grid_parameters.num_columns = 4
make_grid_parameters.num_rows = 5
make_grid_parameters.angle = 0.0
make_grid_parameters.origin_x = 0.0
make_grid_parameters.origin_y = 0.0
make_grid_parameters.block_size_x = 100.0
make_grid_parameters.block_size_y = 100.0
mk.curvilinear_compute_rectangular_grid(make_grid_parameters)
```
将曲线网格转换为非结构网格,并获取生成的 `mesh2d`。
```python
mk.curvilinear_convert_to_mesh2d()
mesh2d_input = mk.mesh2d_get()
```
生成的网格可以按如下方式可视化。
```python
fig, ax = plt.subplots()
mesh2d_input.plot_edges(ax, color="black")
```
![单元格 8 的绘图输出](images/05_mesh2d_refinement_gridded_samples_8_0.png)
定义均匀间距的网格采样数据。
```python
gridded_samples = GriddedSamples(
num_x=5,
num_y=6,
x_origin=-50.0,
y_origin=-50.0,
cell_size=100.0,
values=np.array([-0.05] * 42, dtype=np.float32),
)
```
设置网格加密算法的参数。
```python
refinement_params = MeshRefinementParameters(
refine_intersected=False,
use_mass_center_when_refining=False,
min_edge_size=2.0,
refinement_type=RefinementType.WAVE_COURANT,
connect_hanging_nodes=True,
account_for_samples_outside_face=False,
max_refinement_iterations=5,
)
```
现在可以执行加密。
```python
mk.mesh2d_refine_based_on_gridded_samples(gridded_samples, refinement_params, True)
```
绘制加密后的网格。
```python
mesh2d_output = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_output.plot_edges(ax, color="black")
```
![单元格 16 的绘图输出](images/05_mesh2d_refinement_gridded_samples_16_0.png)
如果采样网格间距不均匀,可以省略部分 `GriddedSamples` 参数,以另一种方式创建网格采样数据。
首先重新生成初始网格。
```python
mk.curvilinear_compute_rectangular_grid(make_grid_parameters)
mk.curvilinear_convert_to_mesh2d()
```
```python
fig, ax = plt.subplots()
mesh2d_input.plot_edges(ax, color="black")
```
![单元格 19 的绘图输出](images/05_mesh2d_refinement_gridded_samples_19_0.png)
当采样网格的 x 或 y 方向间距不均匀时,可以使用 `x_coordinates` 和 `y_coordinates` 参数指定非均匀间距。
```python
gridded_samples = GriddedSamples(
x_coordinates=np.array([-50.0, 50.0, 150.0, 250.0, 350.0, 450.0], dtype=np.double),
y_coordinates=np.array(
[-50.0, 50.0, 150.0, 250.0, 350.0, 450.0, 550.0], dtype=np.double
),
values=np.array([-0.05] * 42, dtype=np.float32),
)
```
```python
mk.mesh2d_refine_based_on_gridded_samples(gridded_samples, refinement_params, True)
```
```python
mesh2d_output = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_output.plot_edges(ax, color="black")
```
![单元格 23 的绘图输出](images/05_mesh2d_refinement_gridded_samples_23_0.png)
@@ -0,0 +1,247 @@
# 基于不同水深精度的 GEBCO 网格采样数据进行二维网格加密
本教程简要介绍如何使用 GEBCO 全球数据集中的网格采样数据进行网格加密。
同时演示以下操作:
1. 在指定范围内生成网格。
2. 将生成的网格保存为 UGrid 文件。
3. 从大型 NetCDF 文件中读取水深数据。
4. 根据均匀间距水深采样数据(较快)或非均匀间距水深采样数据(较慢)进行网格加密。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
导入所需的库,并关闭所有图窗。
```python
import meshkernel
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
```
# 1. 在指定范围内生成网格
```python
# 通用设置
lon_min, lon_max = -1, -0.2
lat_min, lat_max = 49.1, 49.6
lon_res, lat_res = 0.1, 0.1
figsize = (10, 4)
crs = "EPSG:4326"
"""
Make a regular (potentially rotated) rectilinear grid. First generate a curvilinear grid than convert the curvilinear grid into unstructured grid. The steps are the following:
- curvilinear_compute_uniform_on_extension, see the following notebook: https://github.com/Deltares/MeshKernelPy/blob/AddCurvilinearGridSupport/docs/examples/04_curvilineargrid_basics.ipynb
- curvilinear_convert_to_mesh2d: https://github.com/Deltares/MeshKernelPy/blob/118cb4953c4e95d5b18ed283bb37f391134b2bb2/meshkernel/meshkernel.py#L1399
"""
# 创建 MakeGridParameters 实例并设置参数值
make_grid_parameters = meshkernel.MakeGridParameters()
make_grid_parameters.origin_x = lon_min
make_grid_parameters.origin_y = lat_min
make_grid_parameters.upper_right_x = lon_max
make_grid_parameters.upper_right_y = lat_max
make_grid_parameters.block_size_x = lon_res
make_grid_parameters.block_size_y = lat_res
mk2 = meshkernel.MeshKernel(projection=meshkernel.ProjectionType.SPHERICAL)
mk2.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
mk2.curvilinear_convert_to_mesh2d() # 转换为 UGrid/二维网格
mesh2d = mk2.mesh2d_get()
fig, ax = plt.subplots()
mesh2d.plot_edges(ax)
```
![单元格 4 的绘图输出](images/06_mesh2d_refinement_gridded_samples_gebco_4_0.png)
# 2. 将生成的网格保存为 UGrid 文件
可以使用以下代码将生成的网格保存为 UGrid 文件。执行这些代码前,需要安装 UGrid Python 包。
```python
ugrid_installed = False
if ugrid_installed:
from ugrid import UGrid, UGridMesh2D
mesh2d_ugrid = UGrid.from_meshkernel_mesh2d_to_ugrid_mesh2d(
mesh2d=mesh2d, name="mesh2d", is_spherical=True
)
attribute_dict = {
"name": "Unknown projected",
"epsg": np.array([4326], dtype=int),
"grid_mapping_name": "Unknown projected",
"longitude_of_prime_meridian": np.array([0.0], dtype=float),
"semi_major_axis": np.array([6378137.0], dtype=float),
"semi_minor_axis": np.array([6356752.314245], dtype=float),
"inverse_flattening": np.array([6356752.314245], dtype=float),
"EPSG_code": "EPSG:4326",
"value": "value is equal to EPSG code",
}
with UGrid("./gebco_mesh2d_net.nc", "w+") as ug:
# 1. 定义新的二维网格
topology_id = ug.mesh2d_define(mesh2d_ugrid)
# 3. 写入新的二维网格
ug.mesh2d_put(topology_id, mesh2d_ugrid)
# 3. 将坐标参考系统添加到文件
ug.variable_int_with_attributes_define("wgs84", attribute_dict)
# 4. 添加数据约定(全局属性)
conventions = {
"institution": "Deltares",
"references": "Unknown",
"source": "Unknown Unknown. Model: Unknown",
"history": "Created on 2017-11-27T18:05:09+0100, Unknown",
"Conventions": "CF-1.6 UGRID-1.0/Deltares-0.8",
}
ug.attribute_global_define(conventions)
```
# 3. 从大型 NetCDF 文件中读取水深数据
可以使用 `xarray` 从大型数据集中读取水深数据,它支持仅加载选定区域的数据。当按非均匀间距处理经纬度数组时,双线性插值的速度较慢。
```python
# 选择并绘制水深数据
uniform_grid_spacing = False
if not uniform_grid_spacing:
import xarray as xr
file_nc_bathy = r"p:\metocean-data\open\GEBCO\2021\GEBCO_2021.nc"
data_bathy = xr.open_dataset(file_nc_bathy)
data_bathy_sel = data_bathy.sel(
lon=slice(lon_min - 1 / 4, lon_max + 1 / 4),
lat=slice(lat_min - 1 / 4, lat_max + 1 / 4),
)
lon_np = data_bathy_sel.lon.to_numpy().flatten().astype("float")
lat_np = data_bathy_sel.lat.to_numpy().flatten().astype("float")
values_np = data_bathy_sel.elevation.to_numpy().flatten().astype("float32")
```
另一种方式是从 ASCII 文件读取数据,并假设采样间距均匀。
```python
def read_asc_file(file_path, dtype=np.float32):
"""读取 ASC 文件,返回文件头和 NumPy 数组形式的数据。
参数:
file_path (str):文件路径。
返回值:
header:ASCII 文件头。
data:以双精度 NumPy 数组表示的 ASCII 数据。
"""
header = {}
data = []
with open(file_path, "r") as file:
# 读取文件头信息
for _ in range(6):
line = file.readline().strip().split()
header[line[0]] = float(line[1])
# 读取数据值
for line in file:
data_row = [float(value) for value in line.strip().split()]
data.insert(0, data_row) # 将该行插入到开头
# 将数据展平
data = np.array(data).flatten().astype(dtype)
return header, data
```
# 4. 基于网格采样数据进行加密:水深类型为 np.float32 或 np.int16
将文件中的水深读取为 `np.float32`。
```python
header, values_np = read_asc_file("./data_examples/gebco.asc", dtype=np.float32)
```
将文件中的水深读取为 `np.int16`。
```python
header, values_np = read_asc_file("./data_examples/gebco.asc", dtype=np.int16)
```
采样网格属性。
```python
num_x = int(header["ncols"])
num_y = int(header["nrows"])
x_origin = header["xllcenter"]
y_origin = header["yllcenter"]
```
网格采样数据。
```python
gridded_samples = meshkernel.GriddedSamples(
num_x=num_x,
num_y=num_y,
x_origin=x_origin,
y_origin=y_origin,
cell_size=0.0041666666666,
values=values_np,
)
```
另一种方式是通过非均匀间距的 x、y 坐标数组生成网格采样数据。
```python
if not uniform_grid_spacing:
gridded_samples = meshkernel.GriddedSamples(
x_coordinates=lon_np,
y_coordinates=lat_np,
num_x=len(lon_np),
num_y=len(lat_np),
values=values_np,
)
```
定义网格加密参数。
```python
mesh_refinement_parameters = meshkernel.MeshRefinementParameters(
refine_intersected=False,
use_mass_center_when_refining=False,
min_edge_size=500,
refinement_type=meshkernel.RefinementType.WAVE_COURANT,
connect_hanging_nodes=True,
account_for_samples_outside_face=False,
max_refinement_iterations=3,
smoothing_iterations=5,
max_courant_time=120.0,
directional_refinement=0,
)
```
执行加密,此处使用双线性插值。
```python
mk2.mesh2d_refine_based_on_gridded_samples(
gridded_samples=gridded_samples,
mesh_refinement_params=mesh_refinement_parameters,
use_nodal_refinement=True,
)
```
绘制加密后的网格。
```python
# 放大绘图,以观察零散的海岸线
fig1 = plt.figure(figsize=(16, 12))
ax1 = fig1.add_subplot(111)
mesh2d_grid2 = mk2.mesh2d_get()
mesh2d_grid2.plot_edges(ax1, linewidth=1)
```
![单元格 29 的绘图输出](images/06_mesh2d_refinement_gridded_samples_gebco_29_0.png)
@@ -0,0 +1,97 @@
# 在指定范围内生成曲线网格
本教程简要介绍如何在指定范围内生成曲线网格。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
首先导入所需的库。
```python
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import (
GeometryList,
GriddedSamples,
MakeGridParameters,
MeshKernel,
MeshRefinementParameters,
ProjectionType,
RefinementType,
)
```
## 在球面坐标系中创建曲线网格
网格从原点延伸到右上角,自动计算行数和列数,并调整纬度,使实际距离上的纵横比接近 1。
```python
lon_min, lon_max = -1, -0.2
lat_min, lat_max = 49.1, 49.6
lon_res, lat_res = 0.1, 0.1
make_grid_parameters = MakeGridParameters()
make_grid_parameters.origin_x = lon_min
make_grid_parameters.origin_y = lat_min
make_grid_parameters.upper_right_x = lon_max
make_grid_parameters.upper_right_y = lat_max
make_grid_parameters.block_size_x = lon_res
make_grid_parameters.block_size_y = lat_res
mk = MeshKernel(projection=ProjectionType.SPHERICAL)
mk.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
```
将曲线网格转换为非结构网格。
```python
mk.curvilinear_convert_to_mesh2d()
```
绘制网格。
```python
mesh2d = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d.plot_edges(ax, color="black")
```
![单元格 9 的绘图输出](images/07_curvilineargrid_with_defined_extension_9_0.png)
## 在笛卡尔坐标系中创建曲线网格
在笛卡尔坐标系中,无需调整 y 坐标。
```python
min_x, min_y = 0, 0
max_x, max_y = 10.0, 10.0
block_size_x, block_size_y = 1, 2
make_grid_parameters = MakeGridParameters()
make_grid_parameters.origin_x = min_x
make_grid_parameters.origin_y = min_y
make_grid_parameters.upper_right_x = max_x
make_grid_parameters.upper_right_y = max_y
make_grid_parameters.block_size_x = block_size_x
make_grid_parameters.block_size_y = block_size_y
mk = MeshKernel(projection=ProjectionType.CARTESIAN)
mk.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
```
将曲线网格转换为非结构网格。
```python
mk.curvilinear_convert_to_mesh2d()
```
绘制网格。
```python
mesh2d = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d.plot_edges(ax, color="black")
```
![单元格 16 的绘图输出](images/07_curvilineargrid_with_defined_extension_16_0.png)
@@ -0,0 +1,124 @@
# 大型网格正交化
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
本示例演示如何加载大型二维网格并进行正交化。首先导入所需的库。这里还使用 UGrid 库正确加载二维网格。
```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from meshkernel import (
GeometryList,
MeshKernel,
OrthogonalizationParameters,
ProjectionType,
Mesh2d,
)
from ugrid import UGrid, UGridMesh2D
```
定义正交性阈值和文件名。
```python
orthogonality_criteria = 0.3
input_file = "./Michigan_Huron_ORTHO_mc025_mn5_net.nc"
output_file = "./Michigan_Huron_orthogonality_issues.xyz"
```
读取网格几何数据。
```python
with UGrid(input_file, "r") as ug:
num_mesh2d_topologies = ug.mesh2d_get_num_topologies()
mesh2d_ugrid = ug.mesh2d_get(num_mesh2d_topologies - 1)
```
根据节点和边创建 `meshkernel` 的二维网格。
```python
mesh2d_mk = Mesh2d()
mesh2d_mk.node_x = mesh2d_ugrid.node_x
mesh2d_mk.node_y = mesh2d_ugrid.node_y
mesh2d_mk.edge_nodes = mesh2d_ugrid.edge_nodes
```
创建 `MeshKernel` 实例。
```python
mk = MeshKernel(ProjectionType.SPHERICAL)
```
设置网格,此调用计算开销较大。
```python
mk.mesh2d_set(mesh2d_mk)
```
获取网格。
```python
mesh2d_output = mk.mesh2d_get()
```
```python
fig, ax = plt.subplots()
mesh2d_output.plot_edges(ax, color="black")
```
![单元格 15 的绘图输出](images/08_mesh2d_orthogonalization_15_0.png)
查询正交性,此调用计算开销较大。
```python
orthogonality = mk.mesh2d_get_orthogonality().values
```
提取正交性指标值高于 `orthogonality_criteria` 的边。
```python
criteria_indices = np.where(orthogonality > orthogonality_criteria)[0]
```
将提取的边保存到文件。
```python
xyz_df = pd.DataFrame([])
xyz_df["edge_x"] = mesh2d_output.edge_x[criteria_indices]
xyz_df["edge_y"] = mesh2d_output.edge_y[criteria_indices]
xyz_df["orthogonality"] = orthogonality[criteria_indices]
xyz_df.to_csv(output_file, index=False, header=False, sep=" ")
```
## 执行正交化
```python
selecting_polygon = GeometryList(
np.empty(0, dtype=np.double), np.empty(0, dtype=np.double)
)
land_boundaries = GeometryList(
np.empty(0, dtype=np.double), np.empty(0, dtype=np.double)
)
```
```python
mk.mesh2d_compute_orthogonalization(
project_to_land_boundary_option=0,
orthogonalization_parameters=OrthogonalizationParameters(outer_iterations=1),
selecting_polygon=selecting_polygon,
land_boundaries=land_boundaries,
)
```
```python
mesh2d_output = mk.mesh2d_get()
```
```python
fig, ax = plt.subplots()
mesh2d_output.plot_edges(ax, color="black")
```
![单元格 26 的绘图输出](images/08_mesh2d_orthogonalization_26_0.png)
@@ -0,0 +1,304 @@
# 网格删除
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
本教程演示球面坐标下的网格删除操作。首先导入所需的库。
```python
import meshkernel
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
import datetime as dt
```
## 删除简单网格
创建矩形网格。
```python
lon_min, lon_max = -2.5, -1.3
lat_min, lat_max = 48.4, 49.0
lon_res, lat_res = 0.01, 0.01
make_grid_parameters = meshkernel.MakeGridParameters()
make_grid_parameters.origin_x = lon_min
make_grid_parameters.origin_y = lat_min
make_grid_parameters.upper_right_x = lon_max
make_grid_parameters.upper_right_y = lat_max
make_grid_parameters.block_size_x = lon_res
make_grid_parameters.block_size_y = lat_res
mk2 = meshkernel.MeshKernel(projection=meshkernel.ProjectionType.SPHERICAL)
mk2.get_projection()
mk2.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
mk2.curvilinear_convert_to_mesh2d()
mesh2d_orig = mk2.mesh2d_get()
```
创建用于删除操作的多边形。
```python
pol_x = np.array(
[
-2.554972,
-2.475056,
-2.488361,
-2.4375,
-2.418417,
-2.319139,
-2.313333,
-2.28625,
-2.336694,
-2.314167,
-2.246722,
-2.213361,
-2.195028,
-2.182472,
-2.157944,
-2.175444,
-2.152528,
-2.125889,
-2.152528,
-2.04925,
-2.057944,
-2.032111,
-2.034639,
-1.997083,
-2.015472,
-1.975028,
-1.962972,
-1.989667,
-1.957139,
-2.015056,
-2.004583,
-2.033,
-1.98925,
-1.992556,
-1.941667,
-1.962972,
-1.935056,
-1.905028,
-1.843389,
-1.837111,
-1.872111,
-1.842528,
-1.771667,
-1.635028,
-1.592528,
-1.511722,
-1.51,
-1.470056,
-1.43,
-1.3575,
-1.412889,
-1.389222,
-1.447583,
-1.453361,
-1.505028,
-1.530056,
-1.570444,
-1.576278,
-1.615444,
-1.580417,
-1.2,
-1.2,
-2.6,
-2.554972,
]
)
pol_y = np.array(
[
48.599583,
48.622889,
48.64625,
48.653722,
48.634556,
48.690389,
48.672083,
48.667444,
48.620389,
48.612111,
48.645444,
48.57375,
48.611222,
48.577889,
48.587472,
48.597472,
48.618722,
48.604528,
48.633694,
48.639583,
48.625833,
48.624972,
48.604944,
48.578306,
48.571667,
48.536222,
48.549944,
48.583333,
48.578306,
48.598722,
48.614111,
48.650806,
48.668722,
48.684583,
48.684583,
48.689972,
48.702917,
48.690417,
48.712083,
48.679972,
48.645806,
48.616222,
48.603722,
48.617889,
48.639611,
48.621222,
48.632056,
48.625417,
48.643722,
48.63375,
48.659139,
48.67625,
48.655389,
48.672083,
48.687056,
48.73125,
48.744167,
48.821639,
48.835806,
48.856639,
48.9,
48.3,
48.3,
48.599583,
]
)
```
执行网格删除。由于网格较大,可能需要约一分钟。
```python
delete_pol_geom = meshkernel.GeometryList(x_coordinates=pol_x, y_coordinates=pol_y)
print("Deleting grid with coastlines: ", end="")
dtstart = dt.datetime.now()
mk2.mesh2d_delete(
geometry_list=delete_pol_geom,
delete_option=meshkernel.DeleteMeshOption.INSIDE_NOT_INTERSECTED,
invert_deletion=False,
)
print(f"{(dt.datetime.now()-dtstart).total_seconds():.2f} sec")
```
```text
Deleting grid with coastlines: 0.02 sec
```
绘制删除后的结果。
```python
plt.close("all")
figsize = (8, 4)
mesh2d = mk2.mesh2d_get()
fig, ax = plt.subplots(figsize=figsize)
mesh2d_orig.plot_edges(ax, color="grey")
mesh2d.plot_edges(ax, color="k")
ax.plot(pol_x, pol_y, "r", linewidth=1)
ax.set_ylim(lat_min - 0.11, lat_max)
```
```text
(48.29, 49.0)
```
![单元格 11 的绘图输出](images/09_mesh2d_deletion_11_1.png)
## 使用全球多边形删除网格
创建矩形网格。
```python
lon_min, lon_max = -6, 2
lat_min, lat_max = 48.5, 51.2
lon_res, lat_res = 0.2, 0.2
make_grid_parameters = meshkernel.MakeGridParameters()
make_grid_parameters.origin_x = lon_min
make_grid_parameters.origin_y = lat_min
make_grid_parameters.upper_right_x = lon_max
make_grid_parameters.upper_right_y = lat_max
make_grid_parameters.block_size_x = lon_res
make_grid_parameters.block_size_y = lat_res
mk = meshkernel.MeshKernel(projection=meshkernel.ProjectionType.SPHERICAL)
mk.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
mk.curvilinear_convert_to_mesh2d()
mesh2d = mk.mesh2d_get()
mesh2d_orig = mk.mesh2d_get()
num_faces_before = len(mesh2d.face_x)
num_columns = int((lat_max - lat_min) / 0.2)
num_rows = int((lon_max - lon_min) / 0.2)
print("num_faces_before ", num_faces_before)
print("num_columns ", num_columns)
print("num_rows ", num_rows)
```
```text
num_faces_before 1120
num_columns 13
num_rows 40
```
导入全球海岸线,约包含 130,000 条线段。
```python
polygon_file_path = Path().absolute() / "data_examples" / "global_coastline.pol"
polygon_np = np.loadtxt(polygon_file_path, comments="*", skiprows=2, dtype=np.double)
pol_x = np.array(polygon_np[:, 0], dtype=np.double)
pol_y = np.array(polygon_np[:, 1], dtype=np.double)
```
```python
print(">> deleting grid with coastlines: ", end="")
dtstart = dt.datetime.now()
delete_pol_geom = meshkernel.GeometryList(x_coordinates=pol_x, y_coordinates=pol_y)
mk.mesh2d_delete(
geometry_list=delete_pol_geom,
delete_option=meshkernel.DeleteMeshOption.INSIDE_NOT_INTERSECTED,
invert_deletion=False,
)
print(f"{(dt.datetime.now()-dtstart).total_seconds():.2f} sec")
```
```text
>> deleting grid with coastlines: 1.36 sec
```
```python
plt.close("all")
figsize = (8, 4)
mesh2d = mk.mesh2d_get()
fig, ax = plt.subplots(figsize=figsize)
mesh2d_orig.plot_edges(ax, color="grey")
mesh2d.plot_edges(ax, color="k")
ax.plot(pol_x, pol_y, "r", linewidth=1)
ax.set_xlim(lon_min, lon_max)
ax.set_ylim(lat_min, lat_max)
num_faces_after = len(mesh2d.face_x)
print("num_faces_after ", num_faces_before)
print("deleted faces ", num_faces_before - num_faces_after)
```
```text
num_faces_after 1120
deleted faces 213
```
![单元格 18 的绘图输出](images/09_mesh2d_deletion_18_1.png)
@@ -0,0 +1,30 @@
# 生成全球网格
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
本教程演示如何在球面坐标系中生成全球网格。
```python
import meshkernel
import matplotlib.pyplot as plt
```
```python
mk = meshkernel.MeshKernel(projection=meshkernel.ProjectionType.SPHERICAL)
mk.mesh2d_make_global(num_longitude_nodes=192, num_latitude_nodes=100)
mesh2d = mk.mesh2d_get()
```
绘制结果。
```python
plt.close("all")
figsize = (20, 10)
mesh2d = mk.mesh2d_get()
fig, ax = plt.subplots(figsize=figsize)
mesh2d.plot_edges(ax, color="k")
```
![单元格 5 的绘图输出](images/10_mesh2d_global_grid_5_0.png)
@@ -0,0 +1,161 @@
# 基于网格采样数据的二维网格脊线加密
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
首先导入所需的库。
```python
import matplotlib.pyplot as plt
import numpy as np
from meshkernel import (
GeometryList,
GriddedSamples,
MakeGridParameters,
MeshKernel,
MeshRefinementParameters,
RefinementType,
GriddedSamples,
)
```
`meshkernel` 提供了一组便捷方法,用于创建常见网格。
这里使用 `curvilinear_compute_rectangular_grid` 方法创建一个简单的曲线网格。该方法的完整参数请参阅相应文档。
```python
mk = MeshKernel()
num_rows = 21
num_columns = 41
make_grid_parameters = MakeGridParameters()
make_grid_parameters.num_columns = num_columns
make_grid_parameters.num_rows = num_rows
make_grid_parameters.angle = 0.0
make_grid_parameters.origin_x = 0.0
make_grid_parameters.origin_y = 0.0
make_grid_parameters.block_size_x = 10.0
make_grid_parameters.block_size_y = 10.0
mk.curvilinear_compute_rectangular_grid(make_grid_parameters)
```
将曲线网格转换为非结构网格,并获取生成的 `mesh2d`。
```python
mk.curvilinear_convert_to_mesh2d()
mesh2d_input = mk.mesh2d_get()
```
生成的网格可以按如下方式可视化。
```python
fig, ax = plt.subplots()
mesh2d_input.plot_edges(ax, color="black")
```
![单元格 8 的绘图输出](images/11_mesh2d_refine_ridges_gridded_samples_8_0.png)
定义均匀间距的网格采样数据。
```python
def read_asc_file(file_path, dtype=np.float32):
"""读取 ASC 文件,返回文件头和 NumPy 数组形式的数据。
参数:
file_path (str):文件路径。
返回值:
header:ASCII 文件头。
data:以双精度 NumPy 数组表示的 ASCII 数据。
"""
header = {}
data = []
with open(file_path, "r") as file:
# 读取文件头信息
for _ in range(6):
line = file.readline().strip().split()
header[line[0]] = float(line[1])
# 读取数据值
for line in file:
data_row = [float(value) for value in line.strip().split()]
data.insert(0, data_row) # 将该行插入到开头
# 将数据展平
data = np.array(data).flatten().astype(dtype)
return header, data
```
```python
header, values_np = read_asc_file("./data_examples/gaussian_bump.asc", dtype=np.float32)
```
绘制从 ASC 文件读取的数据。
```python
values_np_matrix = np.reshape(values_np, (int(header["nrows"]), int(header["ncols"])))
plt.imshow(values_np_matrix, cmap="viridis", interpolation="nearest")
plt.title("gaussian bump")
plt.show()
```
![单元格 13 的绘图输出](images/11_mesh2d_refine_ridges_gridded_samples_13_0.png)
假设间距均匀,将 ASCII 数据存入 `GriddedSamples` 实例。
```python
num_sample_x_coordinates = (num_columns - 1) * 2 + 1
num_sample_y_coordinates = (num_rows - 1) * 2 + 1
gridded_samples = GriddedSamples(
num_x=num_sample_x_coordinates,
num_y=num_sample_y_coordinates,
x_origin=0.0,
y_origin=-0.0,
cell_size=5.0,
values=values_np,
)
```
设置网格加密算法的参数。注意,必须正确设置脊线加密类型。
```python
refinement_params = MeshRefinementParameters(
refine_intersected=False,
use_mass_center_when_refining=False,
min_edge_size=2.0,
refinement_type=RefinementType.RIDGE_DETECTION,
connect_hanging_nodes=True,
account_for_samples_outside_face=False,
max_refinement_iterations=1,
)
```
现在可以执行加密。
```python
relative_search_radius = 1.01
minimum_num_samples = 1
number_of_smoothing_iterations = 0
mk.mesh2d_refine_ridges_based_on_gridded_samples(
gridded_samples=gridded_samples,
relative_search_radius=relative_search_radius,
minimum_num_samples=minimum_num_samples,
number_of_smoothing_iterations=number_of_smoothing_iterations,
mesh_refinement_params=refinement_params,
)
```
绘制加密后的网格。
```python
mesh2d_output = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_output.plot_edges(ax, color="black")
```
![单元格 21 的绘图输出](images/11_mesh2d_refine_ridges_gridded_samples_21_0.png)
@@ -0,0 +1,125 @@
# 基于含海岸线的网格采样数据进行二维网格加密
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
```python
import matplotlib.pyplot as plt
plt.close("all")
import xarray as xr
import numpy as np
import meshkernel
import contextily as ctx
from meshkernel import (
MakeGridParameters,
MeshKernel,
GriddedSamples,
ProjectionType,
MeshRefinementParameters,
RefinementType,
)
mk_version = meshkernel.__version__
```
### 水深采样数据
```python
# GEBCO 水深采样数据
lon_np = np.array(
[
-68.54791667,
-68.46458333,
-68.38125,
-68.29791667,
-68.21458333,
-68.13125,
-68.04791667,
-67.96458333,
]
)
lat_np = np.array(
[
11.80208333,
11.88541667,
11.96875,
12.05208333,
12.13541667,
12.21875,
12.30208333,
12.38541667,
12.46875,
12.55208333,
]
)
values_np_2d = np.array(
[
[-1700, -1769, -1688, -1641, -1526, -1291, -1121, -1537],
[-1561, -1674, -1354, -757, -837, -838, -1080, -1466],
[-1630, -1390, -710, -562, -479, -753, -1246, -1703],
[-1553, -1446, -1147, -248, -175, -712, -1621, -1920],
[-1503, -1380, -1080, -305, 18, -543, -1563, -2241],
[-1477, -1571, -3, 100, 11, -891, -1521, -2446],
[-1892, -1808, 16, -3102, -2015, -1302, -1484, -2581],
[-2516, -2091, -1957, -2647, -1422, -1486, -2340, -2702],
[-2689, -2353, -2614, -3612, -3058, -3017, -3181, -2848],
[-3110, -3025, -3861, -3927, -3818, -4162, -4386, -4504],
]
)
values_np = values_np_2d.flatten().astype(np.float32)
```
### 生成规则网格
```python
lon_min, lon_max, lat_min, lat_max = -68.55, -67.9, 11.8, 12.6
dx = dy = 0.05
make_grid_parameters = MakeGridParameters(
angle=0,
origin_x=lon_min,
origin_y=lat_min,
upper_right_x=lon_max,
upper_right_y=lat_max,
block_size_x=dx,
block_size_y=dy,
)
mk = MeshKernel(projection=ProjectionType(1))
mk.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
mk.curvilinear_convert_to_mesh2d() # 转换为 UGrid/二维网格
```
### 执行加密
```python
gridded_samples = GriddedSamples(
x_coordinates=lon_np, y_coordinates=lat_np, values=values_np
)
```
```python
mesh_refinement_parameters = MeshRefinementParameters(
min_edge_size=300, # 单位始终为米
refinement_type=RefinementType(1), # 波动库朗数加密类型,枚举值为 1
connect_hanging_nodes=True, # 设为 False 可分多步加密,例如分别处理多个区域
smoothing_iterations=2,
max_courant_time=120,
)
```
```python
mk.mesh2d_refine_based_on_gridded_samples(
gridded_samples=gridded_samples,
mesh_refinement_params=mesh_refinement_parameters,
use_nodal_refinement=True,
)
```
```python
fig, ax = plt.subplots()
mk.mesh2d_get().plot_edges(ax=ax, linewidth=1)
```
![单元格 10 的绘图输出](images/12_mesh2d_refine_gridded_samples_coastlines_10_0.png)
@@ -0,0 +1,82 @@
# 基于带步长数组的网格采样数据进行二维网格加密
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
```python
import matplotlib.pyplot as plt
plt.close("all")
import numpy as np
from meshkernel import (
MeshKernel,
ProjectionType,
MakeGridParameters,
GriddedSamples,
MeshRefinementParameters,
RefinementType,
)
import xarray as xr
```
### 导入水深采样数据并生成内存不连续的数组
```python
lon_min, lon_max, lat_min, lat_max = 142, 150, -42, -39
dxy = 0.5
file_nc_bathy = r"p:\metocean-data\open\GEBCO\2021\GEBCO_2021.nc"
data_bathy = xr.open_dataset(file_nc_bathy)
data_bathy_sel = data_bathy.sel(
lon=slice(lon_min, lon_max, 10), lat=slice(lat_min, lat_max, 10)
).elevation
```
### 生成矩形网格
```python
# 创建基础网格
make_grid_parameters = MakeGridParameters(
angle=0,
origin_x=lon_min,
origin_y=lat_min,
upper_right_x=lon_max,
upper_right_y=lat_max,
block_size_x=dxy,
block_size_y=dxy,
)
mk = MeshKernel(projection=ProjectionType(1))
mk.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
mk.curvilinear_convert_to_mesh2d()
```
### 加密网格
```python
lon_np = data_bathy_sel.lon.to_numpy()
lat_np = data_bathy_sel.lat.to_numpy()
values_np = data_bathy_sel.to_numpy().flatten().astype(np.float32)
gridded_samples = GriddedSamples(
x_coordinates=lon_np, y_coordinates=lat_np, values=values_np
)
# 网格加密
mesh_refinement_parameters = MeshRefinementParameters(
min_edge_size=1000, refinement_type=RefinementType.WAVE_COURANT
)
mk.mesh2d_refine_based_on_gridded_samples(
gridded_samples=gridded_samples, mesh_refinement_params=mesh_refinement_parameters
)
```
### 绘制加密后的网格
```python
fig, ax = plt.subplots()
mk.mesh2d_get().plot_edges(ax=ax, linewidth=1)
```
![单元格 9 的绘图输出](images/13_mesh2d_refine_gridded_samples_strided_arrays_9_0.png)
@@ -0,0 +1,137 @@
# 生成一维与二维网格之间的连接
本教程介绍使用 `meshkernel` 生成网格连接的基本方法。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
```python
from meshkernel import MakeGridParameters, Mesh1d, Mesh2d, MeshKernel, GeometryList
from meshkernel.version import __version__
__version__
```
```text
'7.0.4'
```
导入其他所需的库。
```python
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
```
```python
def plot_mesh_and_contacts(mesh1d_output_0, mesh2d_output_0, contacts_output_0=None):
fig, ax = plt.subplots()
mesh1d_output_0.plot_edges(ax, color="blue")
mesh2d_output_0.plot_edges(ax, color="black")
if contacts_output_0:
contacts_output_0.plot_edges(ax, mesh1d_output_0, mesh2d_output_0, color="red")
ax.plot(
mesh1d_output_0.node_x, mesh1d_output_0.node_y, "o", color="blue", markersize=5
)
plt.show()
```
# 设置二维网格和一维网格
```python
# 创建基础网格
mk = MeshKernel()
make_grid_parameters = MakeGridParameters(
angle=0,
origin_x=0.0,
origin_y=0.0,
upper_right_x=100.0,
upper_right_y=100.0,
block_size_x=10.0,
block_size_y=10.0,
)
mk.curvilinear_compute_rectangular_grid_on_extension(make_grid_parameters)
mk.curvilinear_convert_to_mesh2d()
mesh1d_node_x = [0.0, 50.0, 100.0]
mesh1d_node_y = [20.0, 20.0, 20.0]
mesh1d_edge_nodes = [0, 1, 1, 2]
mesh1d = Mesh1d(
node_x=mesh1d_node_x, node_y=mesh1d_node_y, edge_nodes=mesh1d_edge_nodes
)
mk.mesh1d_set(mesh1d)
```
```python
mesh1d_output_0 = mk.mesh1d_get()
mesh2d_output_0 = mk.mesh2d_get()
contacts_output_0 = mk.contacts_get()
plot_mesh_and_contacts(mesh1d_output_0, mesh2d_output_0, contacts_output_0)
```
![单元格 7 的绘图输出](images/14_contacts_generation_7_0.png)
## 计算连接
```python
node_mask = np.full(mesh1d.node_x.size, True)
```
#### 计算多重连接
```python
mk.contacts_compute_multiple(node_mask)
mesh1d_output_0 = mk.mesh1d_get()
mesh2d_output_0 = mk.mesh2d_get()
contacts_output_0 = mk.contacts_get()
plot_mesh_and_contacts(mesh1d_output_0, mesh2d_output_0, contacts_output_0)
```
![单元格 11 的绘图输出](images/14_contacts_generation_11_0.png)
#### 计算单一连接
```python
x_coordinates = np.array([0.0, 100.0, 100.0, 0.0, 0.0], dtype=np.double)
y_coordinates = np.array([0.0, 0.0, 100.0, 100.0, 0.0], dtype=np.double)
area_selection = GeometryList(x_coordinates, y_coordinates)
mk.contacts_compute_single(node_mask, area_selection, projection_factor=0.0)
mesh1d_output_0 = mk.mesh1d_get()
mesh2d_output_0 = mk.mesh2d_get()
contacts_output_0 = mk.contacts_get()
plot_mesh_and_contacts(mesh1d_output_0, mesh2d_output_0, contacts_output_0)
```
![单元格 13 的绘图输出](images/14_contacts_generation_13_0.png)
#### 根据指定点计算连接
```python
x_coordinates = np.array([10.000001], dtype=np.double)
y_coordinates = np.array([5.0], dtype=np.double)
point_cloud = GeometryList(x_coordinates, y_coordinates)
mk.contacts_compute_with_points(node_mask, point_cloud)
mesh1d_output_0 = mk.mesh1d_get()
mesh2d_output_0 = mk.mesh2d_get()
contacts_output_0 = mk.contacts_get()
plot_mesh_and_contacts(mesh1d_output_0, mesh2d_output_0, contacts_output_0)
```
![单元格 15 的绘图输出](images/14_contacts_generation_15_0.png)
### 计算边界连接
```python
mk.contacts_compute_boundary(node_mask, search_radius=50.0)
mesh1d_output_0 = mk.mesh1d_get()
mesh2d_output_0 = mk.mesh2d_get()
contacts_output_0 = mk.contacts_get()
plot_mesh_and_contacts(mesh1d_output_0, mesh2d_output_0, contacts_output_0)
```
![单元格 17 的绘图输出](images/14_contacts_generation_17_0.png)
@@ -0,0 +1,255 @@
# 基于水深的二维网格 Casulli 加密
!!! note "接口版本差异"
原示例代码使用旧名称 `mkernel_set_property` 和 `mkernel_mesh2d_casulli_refinement_based_on_depths`。当前 8.3.0 源码中的对应接口为 `mesh2d_set_property` 和 `mesh2d_casulli_refinement_based_on_depths`;实际运行时请依据 [完整 API 参考](../api/meshkernel.meshkernel.md) 调整。以下保留原示例代码。
[返回示例目录](index.md)
以下保留原笔记本的代码和已保存输出;转换过程中未重新执行代码。
```python
import matplotlib.pyplot as plt
from pathlib import Path
plt.close("all")
import xarray as xr
import numpy as np
import meshkernel
from meshkernel import (
MakeGridParameters,
MeshKernel,
GeometryList,
GriddedSamples,
ProjectionType,
MeshRefinementParameters,
RefinementType,
InterpolationType,
InterpolationParameters,
)
mk_version = meshkernel.__version__
```
# 示例 1:加密笛卡尔坐标网格
```python
mk = MeshKernel(ProjectionType.CARTESIAN)
x_start, x_end = 0, 10000
y_min, y_max = 0, 10000
num_samples = 100
makeGridParameters = MakeGridParameters()
makeGridParameters.origin_x = x_start
makeGridParameters.origin_y = y_min
makeGridParameters.upper_right_x = x_end
makeGridParameters.upper_right_y = y_max
makeGridParameters.block_size_x = 1000
makeGridParameters.block_size_y = 1000
mk.mesh2d_make_rectangular_mesh_on_extension(makeGridParameters)
```
### 绘制初始笛卡尔坐标网格
```python
mesh2d_not_refined = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_not_refined.plot_edges(ax)
```
![单元格 5 的绘图输出](images/15_mesh2d_refinement_casulli_based_on_depths_5_0.png)
```python
x_grid, y_grid = np.meshgrid(
np.linspace(x_start, x_end, num_samples), np.linspace(y_min, y_max, num_samples)
)
values = np.array(np.interp(x_grid, [x_start, x_end], [-10.0, 5.0]), dtype=np.double)
```
### 绘制采样数据集
```python
plt.figure(figsize=(8, 6))
plt.contourf(x_grid, y_grid, values, levels=50)
```
```text
<matplotlib.contour.QuadContourSet at 0x1f054cec790>
```
![单元格 8 的绘图输出](images/15_mesh2d_refinement_casulli_based_on_depths_8_1.png)
```python
samples = GeometryList(
x_coordinates=np.array(x_grid.flatten(), dtype=np.double),
y_coordinates=np.array(y_grid.flatten(), dtype=np.double),
values=np.array(values.flatten(), dtype=np.double),
)
interpolation_parameters = InterpolationParameters()
interpolation_parameters.interpolation_type = InterpolationType.AVERAGING
property_id = mk.mkernel_set_property(interpolation_parameters, samples)
x_coordinates_pol = np.empty(0, dtype=np.double)
y_coordinates_pol = np.empty(0, dtype=np.double)
polygons = GeometryList(
x_coordinates=x_coordinates_pol, y_coordinates=y_coordinates_pol
)
meshRefinementParameters = MeshRefinementParameters()
minimumRefinementDepth = 0.0
mk.mkernel_mesh2d_casulli_refinement_based_on_depths(
polygons, property_id, meshRefinementParameters, minimumRefinementDepth
)
```
### 绘制加密后的网格(应能看到变化)
```python
mesh2d_refined = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_refined.plot_edges(ax)
```
![单元格 11 的绘图输出](images/15_mesh2d_refinement_casulli_based_on_depths_11_0.png)
# 示例 2:使用较小区域的真实水深数据进一步细化分析
## 读取采样数据的辅助函数
```python
def read_and_filter_samples(file_path, lower_left, upper_right):
"""
读取包含采样数据(纬度、经度、水深)的文本文件,筛选边界框内的采样点,
返回三个双精度 NumPy 数组(纬度、经度、水深)。
:param file_path: 包含数据的文本文件路径。
:param lower_left: 边界框左下角的(纬度、经度)元组。
:param upper_right: 边界框右上角的(纬度、经度)元组。
:return: 包含纬度、经度、水深三个 NumPy 数组的元组。
"""
latitudes = []
longitudes = []
depths = []
# 解包边界框角点坐标
ll_lat, ll_long = lower_left
ur_lat, ur_long = upper_right
try:
with open(file_path, "r") as file:
for line in file:
# 将该行解析为纬度、经度和水深
parts = line.strip().split("\t")
if len(parts) != 3:
continue
try:
lat, long, depth = map(float, parts)
except ValueError:
continue
# 检查采样点是否位于边界框内
if ll_lat <= lat <= ur_lat and ll_long <= long <= ur_long:
latitudes.append(lat)
longitudes.append(long)
depths.append(depth)
except FileNotFoundError:
print(f"Error: File {file_path} not found.")
return (
np.array([], dtype=np.double),
np.array([], dtype=np.double),
np.array([], dtype=np.double),
)
except Exception as e:
print(f"An error occurred: {e}")
return (
np.array([], dtype=np.double),
np.array([], dtype=np.double),
np.array([], dtype=np.double),
)
# 将列表转换为 double 类型的 NumPy 数组
return (
np.array(latitudes, dtype=np.double),
np.array(longitudes, dtype=np.double),
np.array(depths, dtype=np.double),
)
```
```python
input_file = "stpete.xyz"
input_file_path = Path().absolute() / "data_examples" / input_file
lower_left_corner = (-82.79428, 28.00218)
upper_right_corner = (-82.76323, 28.02404)
# 读取并筛选采样数据
x_coordinates, y_coordinates, values = read_and_filter_samples(
input_file_path, lower_left_corner, upper_right_corner
)
```
### 生成规则网格
```python
lon_min, lon_max, lat_min, lat_max = -82.79428, -82.76323, 28.00218, 28.02404
dx = (lon_max - lon_min) / 10.0
dy = (lat_max - lat_min) / 10.0
makeGridParameters = MakeGridParameters(
angle=0,
origin_x=lon_min,
origin_y=lat_min,
upper_right_x=lon_max,
upper_right_y=lat_max,
block_size_x=dx,
block_size_y=dy,
)
mk = MeshKernel(projection=ProjectionType.SPHERICAL)
mk.mesh2d_make_rectangular_mesh(makeGridParameters)
```
```python
mesh2d_not_refined = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_not_refined.plot_edges(ax)
```
![单元格 18 的绘图输出](images/15_mesh2d_refinement_casulli_based_on_depths_18_0.png)
```python
samples = GeometryList(
x_coordinates=x_coordinates, y_coordinates=y_coordinates, values=values
)
```
```python
interpolation_parameters = InterpolationParameters()
interpolation_parameters.interpolation_type = InterpolationType.AVERAGING
property_id = mk.mkernel_set_property(interpolation_parameters, samples)
x_coordinates_pol = np.empty(0, dtype=np.double)
y_coordinates_pol = np.empty(0, dtype=np.double)
polygons = GeometryList(
x_coordinates=x_coordinates_pol, y_coordinates=y_coordinates_pol
)
meshRefinementParameters = MeshRefinementParameters()
minimumRefinementDepth = 0.0
mk.mkernel_mesh2d_casulli_refinement_based_on_depths(
polygons, property_id, meshRefinementParameters, minimumRefinementDepth
)
```
```python
mesh2d_refined = mk.mesh2d_get()
fig, ax = plt.subplots()
mesh2d_refined.plot_edges(ax)
```
![单元格 21 的绘图输出](images/15_mesh2d_refinement_casulli_based_on_depths_21_0.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+21
View File
@@ -0,0 +1,21 @@
# 中文示例教程
以下 15 个教程按原 Jupyter 笔记本顺序译为中文网页,保留示例代码、代码注释与原笔记本已保存的计算结果和绘图。生成文档时未执行示例代码。
若要实际运行示例,可从 [上游示例目录](https://github.com/Deltares/MeshKernelPy/tree/main/docs/examples) 获取笔记本及 `data_examples` 数据。部分示例还依赖 UGrid、xarray、contextily 或外部网格/GEBCO 数据,需要按本机环境调整路径。
- [二维网格基础](01_mesh2d_basics.md)
- [一维网格基础](02_mesh1d_basics.md)
- [在给定几何区域内生成简单三角网格](03_tri_mesh2d_pol.md)
- [曲线网格基础](04_curvilineargrid_basics.md)
- [基于规则网格采样数据的二维网格加密](05_mesh2d_refinement_gridded_samples.md)
- [基于不同水深精度的 GEBCO 网格采样数据进行二维网格加密](06_mesh2d_refinement_gridded_samples_gebco.md)
- [在指定范围内生成曲线网格](07_curvilineargrid_with_defined_extension.md)
- [大型网格正交化](08_mesh2d_orthogonalization.md)
- [网格删除](09_mesh2d_deletion.md)
- [生成全球网格](10_mesh2d_global_grid.md)
- [基于网格采样数据的二维网格脊线加密](11_mesh2d_refine_ridges_gridded_samples.md)
- [基于含海岸线的网格采样数据进行二维网格加密](12_mesh2d_refine_gridded_samples_coastlines.md)
- [基于带步长数组的网格采样数据进行二维网格加密](13_mesh2d_refine_gridded_samples_strided_arrays.md)
- [生成一维与二维网格之间的连接](14_contacts_generation.md)
- [基于水深的二维网格 Casulli 加密](15_mesh2d_refinement_casulli_based_on_depths.md)