# 基于规则网格采样数据的二维网格加密 本教程简要介绍如何使用规则网格采样数据进行网格加密。加密时,通过双线性插值计算网格节点处的水深值。 [返回示例目录](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)