Python_API_os_remove_待填充

本文详细介绍了Python中os模块的remove()函数用法。该函数用于删除文件路径,如果路径指向的是目录,则会引发OSError;在Windows系统下,尝试删除正在使用的文件将触发异常,在Unix系统下则仅移除目录项。
os.remove(path)

Remove (delete) the file path. If path is a directory,OSError is raised; seermdir() below to remove a directory. This is identical to theunlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.


F:\pythonProject\gempy-main.venv\Scripts\python.exe F:\pycharm\3d1.py Setting Backend To: AvailableBackends.numpy Help on package gempy_viewer: NAME gempy_viewer PACKAGE CONTENTS API (package) DEP (package) _version core (package) modules (package) optional_dependencies FUNCTIONS plot_2d(model: gempy.core.data.geo_model.GeoModel, n_axis=None, section_names: list = None, cell_number: Union[int, list[int], str, list[str], NoneType] = None, direction: Union[str, list[str], NoneType] = 'y', series_n: Union[int, List[int]] = 0, legend: bool = True, ve=1, block=None, override_regular_grid=None, kwargs_topography=None, kwargs_lithology=None, kwargs_scalar_field=None, **kwargs) -> gempy_viewer.modules.plot_2d.visualization_2d.Plot2D Plot 2-D sections of the geomodel. This function plots cross-sections either based on custom section traces or cell numbers in the xyz directions. Options are provided to plot lithology blocks, scalar fields, or rendered surface lines. Input data and topography can be included. Args: model (GeoModel): Geomodel object with solutions. n_axis (Optional[int]): Subplot axis for multiple sections. section_names (Optional[List[str]]): Names of predefined custom section traces. cell_number (Optional[Union[int, List[int], str, List[str]]]): Position of the array to plot. direction (Optional[Union[str, List[str]]]): Cartesian direction to be plotted (xyz). series_n (Union[int, List[int]]): Number of the scalar field. legend (bool): If True, plot legend. Defaults to True. ve (float): Vertical exaggeration. Defaults to 1. block (Optional[np.ndarray]): Deprecated. Use regular grid instead. override_regular_grid (Optional[np.ndarray]): Numpy array of the size of model.grid.regular_grid. If provided, the regular grid will be overridden by this array. kwargs_topography (Optional[dict]): Additional keyword arguments for topography. * fill_contour: Fill contour flag. * hillshade (bool): Calculate and add hillshading using elevation data. * azdeg (float): Azimuth of sun for hillshade. - altdeg (float): Altitude in degrees of sun for hillshade. kwargs_lithology (Optional[dict]): Additional keyword arguments for lithology. kwargs_scalar_field (Optional[dict]): Additional keyword arguments for scalar field. Keyword Args: show_block (bool): If True and the model has been computed, plot cross section of the final model. show_values (bool): If True and the model has been computed, plot cross section of the value. show (bool): Call matplotlib show. Defaults to True. show_data (bool): Show original input data. Defaults to True. show_results (bool): If False, override show lithology, scalar field, and values. Defaults to True. show_lith (bool): Show lithological block volumes. Defaults to True. show_scalar (bool): Show scalar field isolines. Defaults to False. show_boundaries (bool): Show surface boundaries as lines. Defaults to True. show_topography (bool): Show topography on plot. Defaults to False. show_section_traces (bool): Show section traces. Defaults to True. Returns: gempy.plot.visualization_2d.Plot2D: Plot2D object. plot_3d(model: gempy.core.data.geo_model.GeoModel, plotter_type: str = 'basic', active_scalar_field: Optional[str] = None, ve: Optional[float] = None, topography_scalar_type: gempy_viewer.core.scalar_data_type.TopographyDataType = <TopographyDataType.GEOMAP: 2>, kwargs_pyvista_bounds: Optional[dict] = None, kwargs_plot_structured_grid: Optional[dict] = None, kwargs_plot_topography: Optional[dict] = None, kwargs_plot_data: Optional[dict] = None, kwargs_plotter: Optional[dict] = None, kwargs_plot_surfaces: Optional[dict] = None, image: bool = False, show: bool = True, transformed_data: bool = False, **kwargs) -> gempy_viewer.modules.plot_3d.vista.GemPyToVista Plot 3-D geomodel. Args: model (GeoModel): Geomodel object with solutions. plotter_type (str): Type of plotter to use. Defaults to 'basic'. active_scalar_field (Optional[str]): Active scalar field for the plot. ve (Optional[float]): Vertical exaggeration. topography_scalar_type (TopographyDataType): Type of topography scalar data. Defaults to TopographyDataType.GEOMAP. kwargs_pyvista_bounds (Optional[dict]): Additional keyword arguments for PyVista bounds. kwargs_plot_structured_grid (Optional[dict]): Additional keyword arguments for plotting the structured grid. kwargs_plot_topography (Optional[dict]): Additional keyword arguments for plotting the topography. kwargs_plot_data (Optional[dict]): Additional keyword arguments for plotting data. kwargs_plotter (Optional[dict]): Additional keyword arguments for the plotter. kwargs_plot_surfaces (Optional[dict]): Additional keyword arguments for plotting surfaces. image (bool): If True, saves the plot as an image. Defaults to False. show (bool): If True, displays the plot. Defaults to True. transformed_data (bool): If True, uses transformed data for plotting. Defaults to False. **kwargs: Additional keyword arguments. Returns: GemPyToVista: Object for 3D plotting in GemPy. plot_section_traces(model: gempy.core.data.geo_model.GeoModel, section_names: list[str] = None) Plot section traces of section grid in 2-D topview (xy). plot_stereonet(self, litho=None, planes=True, poles=True, single_plots=False, show_density=False) plot_topology(regular_grid: gempy.core.data.grid_modules.grid_types.RegularGrid, edges, centroids, direction='y', ax=None, scale=True, label_kwargs=None, edge_kwargs=None) Plot the topology adjacency graph in 2-D. Args: geo_model ([type]): GemPy geomodel instance. edges (Set[Tuple[int, int]]): Set of topology edges. centroids (Dict[int, Array[int, 3]]): Dictionary of topology id's and their centroids. direction (Union["x", "y", "z", optional): Section direction. Defaults to "y". label_kwargs (dict, optional): Keyword arguments for topology labels. Defaults to None. edge_kwargs (dict, optional): Keyword arguments for topology edges. Defaults to None. DATA __all__ = ['plot_2d', 'plot_3d', 'plot_section_traces', 'plot_topology... VERSION 2024.2.0.2 FILE f:\pythonproject\gempy-main.venv\lib\site-packages\gempy_viewer\__init__.py Help on package gempy.API in gempy: NAME gempy.API - # Initialization API PACKAGE CONTENTS _version compute_API examples_generator faults_API gp2_gp3_compatibility (package) grid_API implicit_functions initialization_API io_API map_stack_to_surfaces_API FUNCTIONS add_orientations(geo_model: gempy.core.data.geo_model.GeoModel, x: Sequence[float], y: Sequence[float], z: Sequence[float], elements_names: Sequence[str], pole_vector: Optional[Sequence[numpy.ndarray]] = None, orientation: Optional[Sequence[numpy.ndarray]] = None, nugget: Optional[Sequence[float]] = None) -> gempy.core.data.structural_frame.StructuralFrame Add orientation data to the geological model. This function adds orientation data to the specified geological elements in the model. The orientation can be provided directly as pole vectors or as orientation angles (azimuth, dip, polarity). Optional nugget values can also be specified for each orientation point. Args: geo_model (GeoModel): The geological model to which the orientations will be added. x (Sequence[float]): Sequence of x-coordinates for the orientation points. y (Sequence[float]): Sequence of y-coordinates for the orientation points. z (Sequence[float]): Sequence of z-coordinates for the orientation points. elements_names (Sequence[str]): Sequence of element names corresponding to each orientation point. pole_vector (Optional[Sequence[np.ndarray]]): Sequence of pole vectors for the orientation points. orientation (Optional[Sequence[np.ndarray]]): Sequence of orientation angles (azimuth, dip, polarity) for the orientation points. nugget (Optional[Sequence[float]]): Sequence of nugget values for each orientation point. If not provided, a default value will be used for all points. Returns: StructuralFrame: The updated structural frame of the geological model. Raises: ValueError: If neither pole_vector nor orientation is provided, or if the length of the nugget sequence does not match the lengths of the other input sequences. add_structural_group(model: gempy.core.data.geo_model.GeoModel, group_index: int, structural_group_name: str, elements: list[gempy.core.data.structural_element.StructuralElement], structural_relation: gempy_engine.core.data.stack_relation_type.StackRelationType, fault_relations: gempy.core.data.structural_group.FaultsRelationSpecialCase = <FaultsRelationSpecialCase.OFFSET_ALL: 3>) -> gempy.core.data.structural_frame.StructuralFrame add_surface_points(geo_model: gempy.core.data.geo_model.GeoModel, x: Sequence[float], y: Sequence[float], z: Sequence[float], elements_names: Sequence[str], nugget: Optional[Sequence[float]] = None) -> gempy.core.data.structural_frame.StructuralFrame Add surface points to the geological model. This function adds surface points to the specified geological elements in the model. The points are grouped by element names, and optional nugget values can be specified for each point. Args: geo_model (GeoModel): The geological model to which the surface points will be added. x (Sequence[float]): Sequence of x-coordinates for the surface points. y (Sequence[float]): Sequence of y-coordinates for the surface points. z (Sequence[float]): Sequence of z-coordinates for the surface points. elements_names (Sequence[str]): Sequence of element names corresponding to each surface point. nugget (Optional[Sequence[float]]): Sequence of nugget values for each surface point. If not provided, a default value will be used for all points. Returns: StructuralFrame: The updated structural frame of the geological model. Raises: ValueError: If the length of the nugget sequence does not match the lengths of the other input sequences. calculate_gravity_gradient(centered_grid: gempy_engine.core.data.centered_grid.CenteredGrid, ugal=True) -> numpy.ndarray compute_model(gempy_model: gempy.core.data.geo_model.GeoModel, engine_config: Optional[gempy.core.data.gempy_engine_config.GemPyEngineConfig] = None) -> gempy_engine.core.data.solutions.Solutions Compute the geological model given the provided GemPy model. Args: gempy_model (GeoModel): The GemPy model to compute. engine_config (Optional[GemPyEngineConfig]): Configuration for the computational engine. Defaults to None, in which case a default configuration will be used. Raises: ValueError: If the provided backend in the engine_config is not supported. Returns: Solutions: The computed geological model. compute_model_at(gempy_model: gempy.core.data.geo_model.GeoModel, at: numpy.ndarray, engine_config: Optional[gempy.core.data.gempy_engine_config.GemPyEngineConfig] = None) -> numpy.ndarray Compute the geological model at specific coordinates. Note: This function sets a custom grid and computes the model so be wary of side effects. Args: gempy_model (GeoModel): The GemPy model to compute. at (np.ndarray): The coordinates at which to compute the model. engine_config (Optional[GemPyEngineConfig], optional): Configuration for the computational engine. Defaults to None, in which case a default configuration will be used. Returns: np.ndarray: The computed geological model at the specified coordinates. create_data_legacy(*, project_name: str = 'default_project', extent: Union[list, numpy.ndarray] = None, resolution: Union[list, numpy.ndarray] = None, path_i: str = None, path_o: str = None) -> gempy.core.data.geo_model.GeoModel create_geomodel(*, project_name: str = 'default_project', extent: Union[list, numpy.ndarray] = None, resolution: Union[list, numpy.ndarray] = None, refinement: int = 1, structural_frame: gempy.core.data.structural_frame.StructuralFrame = None, importer_helper: gempy.core.data.importer_helper.ImporterHelper = None) -> gempy.core.data.geo_model.GeoModel Initializes and returns a GeoModel instance with specified parameters. Args: project_name (str, optional): The name of the project. Defaults to 'default_project'. extent (Union[List, np.ndarray], optional): The 3D extent of the grid. Must be provided if resolution is specified. Defaults to None. resolution (Union[List, np.ndarray], optional): The resolution of the grid. If None, an octree grid will be initialized. Defaults to None. refinement (int, optional): The level of refinement for the octree grid. Defaults to 1. structural_frame (StructuralFrame, optional): The structural frame of the GeoModel. Either this or importer_helper must be provided. Defaults to None. importer_helper (ImporterHelper, optional): Helper object for importing structural elements. Either this or structural_frame must be provided. Defaults to None. Returns: GeoModel: The initialized GeoModel object. Raises: ValueError: If neither structural_frame nor importer_helper is provided. create_orientations_from_surface_points_coords(xyz_coords: numpy.ndarray, subset: Optional[numpy.ndarray] = None, element_name: Optional[str] = 'Generated') -> gempy.core.data.orientations.OrientationsTable delete_orientations() delete_surface_points() generate_example_model(example_model: gempy.core.data.enumerators.ExampleModel, compute_model: bool = True) -> gempy.core.data.geo_model.GeoModel map_stack_to_surfaces(gempy_model: gempy.core.data.geo_model.GeoModel, mapping_object: Union[dict[str, list[str]], dict[str, tuple]], set_series: bool = True, remove_unused_series=True) -> gempy.core.data.structural_frame.StructuralFrame Map stack (series) to surfaces by reorganizing elements between groups in a GeoModel's structural frame. This function reorganizes structural elements (surfaces) based on a mapping object and updates the structural frame of the GeoModel. It can also create new series and remove unused ones. Args: gempy_model (GeoModel): The GeoModel object whose structural frame is to be modified. mapping_object (Union[dict[str, list[str]] | dict[str, tuple]]): Dictionary mapping group names to element names. set_series (bool, optional): If True, creates new series for groups not present in the GeoModel. Defaults to True. remove_unused_series (bool, optional): If True, removes groups without any elements. Defaults to True. Returns: StructuralFrame: The updated StructuralFrame object. modify_orientations(geo_model: gempy.core.data.geo_model.GeoModel, slice: Union[int, slice, NoneType] = None, **orientation_field: Union[float, numpy.ndarray]) -> gempy.core.data.structural_frame.StructuralFrame Modifies specified fields of all orientations in the structural frame. The keys of the orientation_field dictionary should match the field names in the orientations (e.g., "X", "Y", "Z", "G_x", "G_y", "G_z", "nugget"). Args: geo_model (GeoModel): The GeoModel instance to modify. slice (Optional[Union[int, slice]]): The slice of orientations to modify. If None, all orientations will be modified. Keyword Args: X (Union[float, np.ndarray]): X coordinates of the orientations. Y (Union[float, np.ndarray]): Y coordinates of the orientations. Z (Union[float, np.ndarray]): Z coordinates of the orientations. azimuth (Union[float, np.ndarray]): Azimuth angles of the orientations. dip (Union[float, np.ndarray]): Dip angles of the orientations. polarity (Union[float, np.ndarray]): Polarity values of the orientations. G_x (Union[float, np.ndarray]): X component of the gradient vector. G_y (Union[float, np.ndarray]): Y component of the gradient vector. G_z (Union[float, np.ndarray]): Z component of the gradient vector. nugget (Union[float, np.ndarray]): Nugget value of the orientations. Returns: StructuralFrame: The modified structural frame. modify_surface_points(geo_model: gempy.core.data.geo_model.GeoModel, slice: Union[int, slice, NoneType] = None, elements_names: Optional[Sequence[str]] = None, **surface_points_field: Union[float, numpy.ndarray]) -> gempy.core.data.structural_frame.StructuralFrame Modifies specified fields of all surface points in the structural frame. The keys of the surface_points_field dictionary should match the field names in the surface points (e.g., "X", "Y", "Z", "nugget"). Args: geo_model (GeoModel): The GeoModel instance to modify. slice (Optional[Union[int, slice]]): The slice of surface points to modify. If None, all surface points will be modified. Keyword Args: X (Union[float, np.ndarray]): X coordinates of the surface points. Y (Union[float, np.ndarray]): Y coordinates of the surface points. Z (Union[float, np.ndarray]): Z coordinates of the surface points. nugget (Union[float, np.ndarray]): Nugget value of the surface points. Returns: StructuralFrame: The modified structural frame. remove_element_by_name(model: gempy.core.data.geo_model.GeoModel, element_name: str) -> gempy.core.data.structural_frame.StructuralFrame remove_structural_group_by_index(model: gempy.core.data.geo_model.GeoModel, group_index: int) -> gempy.core.data.structural_frame.StructuralFrame remove_structural_group_by_name(model: gempy.core.data.geo_model.GeoModel, group_name: str) -> gempy.core.data.structural_frame.StructuralFrame set_active_grid(grid: gempy.core.data.grid.Grid, grid_type: list[gempy.core.data.grid.Grid.GridTypes], reset: bool = False) set_centered_grid(grid: gempy.core.data.grid.Grid, centers: numpy.ndarray, resolution: Sequence[float], radius: Union[float, Sequence[float]]) set_custom_grid(grid: gempy.core.data.grid.Grid, xyz_coord: numpy.ndarray) set_fault_relation(frame: Union[gempy.core.data.geo_model.GeoModel, gempy.core.data.structural_frame.StructuralFrame], rel_matrix: numpy.ndarray) -> gempy.core.data.structural_frame.StructuralFrame Sets the fault relations in the structural frame of the GeoModel. Args: frame (Union[GeoModel, StructuralFrame]): GeoModel or its StructuralFrame to be modified. rel_matrix (np.ndarray): Fault relation matrix to be set. Returns: StructuralFrame: The updated StructuralFrame object. set_is_fault(frame: Union[gempy.core.data.geo_model.GeoModel, gempy.core.data.structural_frame.StructuralFrame], fault_groups: Union[list[str], list[gempy.core.data.structural_group.StructuralGroup]], faults_relation_type: gempy.core.data.structural_group.FaultsRelationSpecialCase = <FaultsRelationSpecialCase.OFFSET_FORMATIONS: 1>, change_color: bool = True) -> gempy.core.data.structural_frame.StructuralFrame Sets given groups as fault in the structural frame of the GeoModel. It can optionally change the color of these groups. Args: frame (Union[GeoModel, StructuralFrame]): GeoModel or its StructuralFrame to be modified. fault_groups (Union[list[str], list[StructuralGroup]]): Groups to be set as faults. faults_relation_type (FaultsRelationSpecialCase, optional): Faults relation type to be set. Defaults to FaultsRelationSpecialCase.OFFSET_FORMATIONS. change_color (bool, optional): If True, changes the color of the fault groups. Defaults to True. Returns: StructuralFrame: The updated StructuralFrame object. set_is_finite_fault(self, series_fault=None, toggle: bool = True) set_section_grid(grid: gempy.core.data.grid.Grid, section_dict: dict) set_topography_from_arrays(grid: gempy.core.data.grid.Grid, xyz_vertices: numpy.ndarray) set_topography_from_file(grid: gempy.core.data.grid.Grid, filepath: str, crop_to_extent: Optional[Sequence] = None) set_topography_from_random(grid: gempy.core.data.grid.Grid, fractal_dimension: float = 2.0, d_z: Optional[Sequence] = None, topography_resolution: Optional[Sequence] = None) Sets the topography of the grid using a randomly generated topography. Args: grid (Grid): The grid object on which to set the topography. fractal_dimension (float, optional): The fractal dimension of the random topography. Defaults to 2.0. d_z (Union[Sequence, None], optional): The sequence of elevation increments for the random topography. If None, a default sequence will be used. Defaults to None. topography_resolution (Union[Sequence, None], optional): The resolution of the random topography. If None, the resolution of the grid's regular grid will be used. Defaults to None. Returns: The topography object that was set on the grid. Example: >>> grid = Grid() >>> set_topography_from_random(grid, fractal_dimension=1.5, d_z=[0.1, 0.2, 0.3], topography_resolution=[10, 10]) Note: If topography_resolution is None, the resolution of the grid's regular grid will be used. If d_z is None, a default sequence of elevation increments will be used. set_topography_from_subsurface_structured_grid(grid: gempy.core.data.grid.Grid, struct: 'subsurface.StructuredData') structural_elements_from_borehole_set(borehole_set: 'subsurface.core.geological_formats.BoreholeSet', elements_dict: dict) -> list[gempy.core.data.structural_element.StructuralElement] Creates a list of StructuralElements from a BoreholeSet. Args: borehole_set (subsurface.core.geological_formats.BoreholeSet): The BoreholeSet object containing the boreholes. elements_dict (dict): A dictionary containing the properties of the structural elements to be created. Returns: list[StructuralElement]: A list of StructuralElement objects created from the borehole set. Raises: ValueError: If a top lithology ID specified in `elements_dict` is not found in the borehole set. DATA __all__ = ['create_data_legacy', 'create_geomodel', 'structural_elemen... FILE f:\pythonproject\gempy-main.venv\lib\site-packages\gempy\api\__init__.py Help on package gempy.core in gempy: NAME gempy.core PACKAGE CONTENTS color_generator data (package) FILE f:\pythonproject\gempy-main.venv\lib\site-packages\gempy\core\__init__.py Help on package gempy_engine.API in gempy_engine: NAME gempy_engine.API PACKAGE CONTENTS _version dual_contouring (package) interp_single (package) model (package) server (package) FILE f:\pythonproject\gempy-main.venv\lib\site-packages\gempy_engine\api\__init__.py Help on package gempy_engine: NAME gempy_engine PACKAGE CONTENTS API (package) _version config core (package) modules (package) optional_dependencies plugins (package) VERSION 2024.2.0 FILE f:\pythonproject\gempy-main.venv\lib\site-packages\gempy_engine\__init__.py Process finished with exit code 0 Gempy的API如上。请问import gempy as gp import gempy_viewer as gpv import pandas as pd import matplotlib.pyplot as plt import os import pyvista as pv import numpy as np from scipy.interpolate import griddata from gempy.core.data.gempy_engine_config import GemPyEngineConfig plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 桌面路径 desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") surface_points_file = "interfaces.csv" orientations_file = "orientations.csv" topography_file = "地表高层点.csv" # 构建完整文件路径 surface_points_path = os.path.join(desktop_path, surface_points_file) orientations_path = os.path.join(desktop_path, orientations_file) topography_path = os.path.join(desktop_path, topography_file) # 检查文件是否存在 print(f"表面点文件存在: {os.path.exists(surface_points_path)}") print(f"方向文件存在: {os.path.exists(orientations_path)}") print(f"地形文件存在: {os.path.exists(topography_path)}") interfaces_df = pd.read_csv(surface_points_path) unique_formations = interfaces_df['formation'].unique() print(f"所有地层类型: {sorted(unique_formations)}") # 创建地质模型 geo_model: gp.data.GeoModel = gp.create_geomodel( project_name='Single_layer_topo', extent=[505000, 505500, 3181000, 3181800, 10, 42], resolution=[50, 50, 50], refinement=4, importer_helper=gp.data.ImporterHelper( path_to_orientations=orientations_path, path_to_surface_points=surface_points_path, ) ) geological_map = { 'Stratigraphic_Series': sorted(unique_formations) # 使用实际数据中的所有地层 } print(f"设置地层序列: {geological_map['Stratigraphic_Series']}") # 使用正确的函数设置地层关系 gp.map_stack_to_surfaces( geo_model, mapping_object=geological_map, set_series=True, remove_unused_series=True ) # 处理地形数据 df = pd.read_csv(topography_path) # 提取X, Y, Z坐标 x = df['X'].values y = df['Y'].values z = df['Z'].values print(f"地形数据点数量: {len(x)}") print(f"X范围: {x.min()} - {x.max()}") print(f"Y范围: {y.min()} - {y.max()}") print(f"Z范围: {z.min()} - {z.max()}") # 获取地质模型的网格坐标 grid = geo_model.grid.regular_grid grid_x = grid.values[:, 0].reshape(grid.resolution[0], grid.resolution[1], grid.resolution[2])[:, :, 0] grid_y = grid.values[:, 1].reshape(grid.resolution[0], grid.resolution[1], grid.resolution[2])[:, :, 0] # 将原始地形数据插值到地质模型网格 grid_z = griddata( (x, y), z, (grid_x, grid_y), method='linear', fill_value=np.nanmean(z) ) print(f"插值后网格形状: {grid_z.shape}") # 创建xyz_vertices数组 - 形状应为(n, 3) # 我们需要将网格坐标和插值后的Z值组合 x_flat = grid_x.flatten() y_flat = grid_y.flatten() z_flat = grid_z.flatten() # 移除任何可能的NaN值 valid_mask = ~np.isnan(z_flat) x_valid = x_flat[valid_mask] y_valid = y_flat[valid_mask] z_valid = z_flat[valid_mask] xyz_vertices = np.column_stack([x_valid, y_valid, z_valid]) print(f"xyz_vertices形状: {xyz_vertices.shape}") # 使用set_topography_from_arrays gp.set_topography_from_arrays( grid=geo_model.grid, xyz_vertices=xyz_vertices ) print("成功使用set_topography_from_arrays设置地形") print("生成2D图...") gpv.plot_2d(geo_model, show_topography=True, section_names=['topography']) plt.show() gp.compute_model(geo_model) print("生成2D图...") gpv.plot_2d(geo_model, show_topography=True, section_names=['topography']) plt.show() gpv.plot_2d(geo_model,direction='x',show_topography=True,show_data=False) plt.show() gpv.plot_2d(geo_model,direction='y',show_topography=True,show_data=False) plt.show() print("生成3D图...") gpv.plot_3d( geo_model, show_topography=True, show_lith=True, show_scalar=True, show_values=True, ve=3 # 关闭图像渲染,可能减少错误 ) plt.show() 这段代码有什么问题?为什么地表与下面地层有空隙,或者说分离
11-07
你的代码整体结构是合理的,使用了 `GemPy` 和 `GemPy-Viewer` 进行三维地质建模,并尝试将实际地形数据(来自 CSV 文件)与地质模型结合。但你提到的问题——**“地表与下面的地层之间有空隙或分离”** 是一个非常典型的 GemPy 建模问题。 我们来一步步分析可能的原因、解决方案,并指出代码中需要修正的关键点。 --- ## ✅ 一、问题本质:为什么地表和地层之间出现空隙? ### 📌 核心原因: > **GemPy 的默认规则是:所有地层都从 `Z = extent[5]`(顶部)开始向下填充,除非被控制点明确限制。如果你设置了外部地形,但没有正确地将表面点投影到该地形上,就会导致“地层漂浮在空中”或者“悬空于地形之上”。** 换句话说: - 你用 `set_topography_from_arrays()` 设置了地形网格 ✅ - 但是:**地质界面点(interfaces.csv)的 Z 值仍然是原始高程下的绝对值,未根据真实地形进行调整** - 而且:**GemPy 不会自动把地层“贴合”到自定义地形上,必须显式告诉它哪些点属于哪个地层 + 在哪里终止** 所以即使你看到 `plot_2d(..., show_topography=True)` 显示了地形线,**这些地形只是可视化图层,不影响计算域内的地质插值逻辑!** --- ## ✅ 二、关键错误定位与修复建议 ### ❌ 错误1:地形设置后未启用为“活动网格” ```python gp.set_topography_from_arrays(grid=geo_model.grid, xyz_vertices=xyz_vertices) ``` ✅ 正确调用了函数,但这只是创建了 `topography` 对象。 ⚠️ **你还必须激活这个地形作为模型的一部分:** ```python # 激活地形网格用于计算 geo_model.set_active_grid('topography', True) ``` 否则,地形仅用于绘图,不参与建模! 👉 添加这行代码: ```python geo_model.set_active_grids(['regular', 'topography']) # 或者 ['basal', 'topography'] ``` > 💡 提示:常见模式是使用 `regular` 网格做主体建模,`topography` 网格裁剪上部边界。 --- ### ❌ 错误2:地层控制点未对齐到真实地形 假设你的 `interfaces.csv` 中某个点坐标是 `(x, y, z)`,其中 `z` 是相对于海平面的高度,而你的地形在这个 `(x,y)` 处的实际高度是 `z_topo`,那么如果 `z < z_topo`,这个点就位于“地下”,不可能出现在地表出露位置 —— 导致矛盾。 更严重的是:**当某一层的地表出露点(interface)低于真实地形时,GemPy 无法理解“它应该刚好接触地形”,而是强行向上下延伸,造成断层般的空隙。** #### ✅ 解决方案:将地表出露点的 Z 坐标强制设为对应位置的地形高程 你需要在读取 `interfaces_df` 后,将其地表点的 `Z` 替换为地形插值得到的 `Z_topo`。 ```python # --- 插值地形并更新 interface 的 Z --- from scipy.interpolate import LinearNDInterpolator # 创建地形插值器 topo_interp = LinearNDInterpolator(list(zip(x, y)), z) # 获取 interface 所在位置 xi = interfaces_df['X'].values yi = interfaces_df['Y'].values # 查询每个 interface 点对应的地形高程 zi_topo = topo_interp(xi, yi) # 只更新那些应出露在地表的地层(比如最上层) surface_formations = ['Layer1'] # ← 替换为你实际最上层的地层名! mask_surface = interfaces_df['formation'].isin(surface_formations) interfaces_df.loc[mask_surface, 'Z'] = zi_topo[mask_surface] ``` 然后重新导入这些 surface points 到模型中。 --- ### ❌ 错误3:未正确指定 `ImporterHelper` 或后续修改点后未刷新数据 你现在是先创建模型再处理数据 → 但此时模型已经从 CSV 加载过一次数据了! ⚠️ `create_geomodel(..., importer_helper=...)` 是在初始化阶段加载数据的。之后你改了 `interfaces_df` 并不会自动同步到 `geo_model`. #### ✅ 解决方法:手动添加 surface points 不要依赖 `importer_helper` 来加载已修改的数据。改为: ```python # 清除旧的数据(可选) # geo_model.reset_surfaces() # 手动添加 surface points gp.add_surface_points( geo_model, x=interfaces_df['X'].values, y=interfaces_df['Y'].values, z=interfaces_df['Z'].values, elements_names=interfaces_df['formation'].values ) ``` 同理,orientation 数据也需手动添加(如有): ```python orientations_df = pd.read_csv(orientations_path) gp.add_orientations( geo_model, x=orientations_df['X'].values, y=orientations_df['Y'].values, z=orientations_df['Z'].values, elements_names=orientations_df['formation'].values, pole_vector=None, orientation=list(zip(orientations_df['azimuth'], orientations_df['dip'], orientations_df['polarity'])) ) ``` --- ### ❌ 错误4:未正确定义地层序列顺序(上下关系) 虽然你用了: ```python geological_map = { 'Stratigraphic_Series': sorted(unique_formations) } ``` 但注意:`sorted()` 是按字母排序!不是地质年代顺序! 例如:`['Layer1', 'Layer2', 'Layer10']` 排序后是 `['Layer1', 'Layer10', 'Layer2']` ❌ #### ✅ 应该手动排序: ```python # 示例:按深度由浅入深(即地表 → 深部) strat_order = ['Layer1', 'Layer2', 'Layer3'] # 手动定义正确顺序 geological_map = {'Stratigraphic_Series': strat_order} ``` --- ### ❌ 错误5:plot_3d 使用不当,不能反映真实情况 你在 `compute_model` 之前就画了 `plot_2d` 和 `plot_3d`,这是无效的! ```python print("生成2D图...") gpv.plot_2d(geo_model, show_topography=True, section_names=['topography']) plt.show() gp.compute_model(geo_model) # ← 计算放在这里太晚了! ``` 📌 必须先 `compute_model` 再绘图! ✅ 正确顺序: ```python gp.compute_model(geo_model) gpv.plot_2d(geo_model, ...) # 显示结果 ``` --- ## ✅ 三、完整修正后的核心流程代码(关键部分) ```python import gempy as gp import gempy_viewer as gpv import pandas as pd import numpy as np import os from scipy.interpolate import LinearNDInterpolator # 路径配置 desktop_path = os.path.expanduser("~\\Desktop") surface_points_path = os.path.join(desktop_path, "interfaces.csv") orientations_path = os.path.join(desktop_path, "orientations.csv") topography_path = os.path.join(desktop_path, "地表高层点.csv") # 读取数据 interfaces_df = pd.read_csv(surface_points_path) orientations_df = pd.read_csv(orientations_path) topo_df = pd.read_csv(topography_path) # 地质分层顺序(务必手动设定!) strat_order = sorted(interfaces_df['formation'].unique()) # 或手动列表 print(f"地层顺序: {strat_order}") # 创建空模型(不通过 importer_helper 加载数据) geo_model = gp.create_geomodel( project_name="With_Real_Topo", extent=[505000, 505500, 3181000, 3181800, 10, 42], resolution=[50, 50, 50] ) # 添加地层 gp.add_surfaces(geo_model, surfaces_list=strat_order) # 设置地层序列关系 gp.map_stack_to_surfaces( geo_model, mapping_object={"Stratigraphic_Series": strat_order}, set_series=True, remove_unused_series=True ) # === 处理真实地形 === x_t, y_t, z_t = topo_df['X'].values, topo_df['Y'].values, topo_df['Z'].values topo_interp = LinearNDInterpolator(list(zip(x_t, y_t)), z_t) # 将地表出露层的 Z 更新为地形高程(假设 Layer1 是最上层) surface_formations = ['Layer1'] # ← 修改为你的最上层名称 mask_surface = interfaces_df['formation'].isin(surface_formations) xi = interfaces_df['X'].values yi = interfaces_df['Y'].values zi_corrected = interfaces_df['Z'].copy().values # 仅更新地表层的 Z 值 zi_interp = topo_interp(xi, yi) valid_mask = ~np.isnan(zi_interp) # 防止外推区域出错 for i in range(len(interfaces_df)): if mask_surface.iloc[i] and valid_mask[i]: zi_corrected[i] = zi_interp[i] # 添加 surface points(使用修正后的 Z) gp.add_surface_points( geo_model, x=xi, y=yi, z=zi_corrected, elements_names=interfaces_df['formation'].values ) # 添加 orientation 数据(可选) gp.add_orientations( geo_model, x=orientations_df['X'].values, y=orientations_df['Y'].values, z=orientations_df['Z'].values, elements_names=orientations_df['formation'].values, orientation=list(zip(orientations_df['azimuth'], orientations_df['dip'], orientations_df['polarity'])) ) # === 设置真实地形网格 === xyz_vertices = np.column_stack([x_t, y_t, z_t]) gp.set_topography_from_arrays(geo_model.grid, xyz_vertices) geo_model.set_active_grids(['regular', 'topography']) # 关键! # === 计算模型 === gp.compute_model(geo_model) # === 绘图 === gpv.plot_2d(geo_model, show_topography=True, section_names=['topography']) plt.show() gpv.plot_3d( geo_model, show_topography=True, show_lith=True, ve=1 ) ``` --- ## ✅ 四、其他建议 | 项目 | 建议 | |------|------| | `resolution` | 若地形复杂,考虑提高分辨率 `[100, 100, 100]` | | 插值方式 | 使用 `RBFInterpolator` 或 `CloughTocher2DInterpolator` 更稳定 | | 模型验证 | 使用 `plot_section_traces()` 查看剖面是否合理 | | 日志调试 | 开启 `gp.config.enable_debug_output()` 查看内部状态 | --- ## ✅ 总结:导致“地层与地形分离”的根本原因 | 原因 | 是否解决 | |------|---------| | 未激活地形网格参与建模 | ❌ → ✅ 加 `set_active_grids` | | 地表点 Z 值未对齐真实地形 | ❌ → ✅ 插值替换 | | 地层顺序错误(字母排序 ≠ 地质顺序) | ❌ → ✅ 手动排序 | | 在 compute_model 前绘图 | ⚠️ → ✅ 移动顺序 | | 使用 importer_helper 后又改数据 | ⚠️ → ✅ 改用手动 add_* | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值