示例#1
0
def test_sample_interfaces_from_raster_error(dem):
    from gemgis.raster import sample_interfaces
    from gemgis.utils import set_extent

    extent = set_extent(0, 972, 0, 1069)

    with pytest.raises(TypeError):
        sample_interfaces(raster=[dem],
                          extent=extent,
                          point_x=[[500, 500], [600, 600], [700, 700]],
                          point_y=[[500, 500], [600, 600], [700, 700]],
                          formation='surface')
    with pytest.raises(TypeError):
        sample_interfaces(raster=dem,
                          extent=[extent],
                          point_x=[[500, 500], [600, 600], [700, 700]],
                          point_y=[[500, 500], [600, 600], [700, 700]],
                          formation='surface')
    with pytest.raises(TypeError):
        sample_interfaces(raster=dem,
                          extent='extent',
                          point_x=([500, 500], [600, 600], [700, 700]),
                          point_y=[[500, 500], [600, 600], [700, 700]],
                          formation='surface')
    with pytest.raises(TypeError):
        sample_interfaces(raster=dem,
                          extent=extent,
                          point_x=[[500, 500], [600, 600], [700, 700]],
                          point_y=[[500, 500], [600, 600], [700, 700]],
                          formation=['surface'])
    with pytest.raises(TypeError):
        sample_interfaces(raster=[dem],
                          extent=extent,
                          formation='surface')
示例#2
0
文件: raster.py 项目: geosaber/gemgis
def clip_by_shape(raster: Union[rasterio.io.DatasetReader, np.ndarray],
                  shape: gpd.geodataframe.GeoDataFrame,
                  save: bool = True,
                  path: str = 'clipped.tif',
                  **kwargs) -> np.ndarray:
    """
    Clipping a rasterio raster or np.ndarray by a given shape
    Args:
        raster: np.ndarray or rasterio object to be clipped
        shape: GeoDataFrame containing the corner points of a shape
        bbox_crs: str containing the crs of the bounding box
        save: bool whether to save the clipped raster or not
        path: str with the path where the rasterio object will be saved
    Kwargs:
        extent_raster: list of the extent of the raster (only for np.ndarray), if no extent is provided, the origin
                        of the array will be set to 0,0
    Return:
        np.ndarray of the clipped area
    """

    # Checking that the raster is of type np.ndarray or a rasterio object
    if not isinstance(raster, (np.ndarray, rasterio.io.DatasetReader)):
        raise TypeError(
            'Raster must be of type np.ndarray or a rasterio object')

    # Checking if shape is of type GeoDataFrame
    if not isinstance(shape, gpd.geodataframe.GeoDataFrame):
        raise TypeError('Shape must be of type GeoDataFrame')

    # Checking if argument save if of type bool
    if not isinstance(save, bool):
        raise TypeError('Saving option must be of type bool')

    # Checking if path is of type string
    if not isinstance(path, str):
        raise TypeError('Path must be of type string')

    # Creating bounding box from shape
    bbox = set_extent(gdf=shape)
    bbox[1] = bbox[1] + 1
    bbox[3] = bbox[3] + 1

    # Getting raster extent
    extent_raster = kwargs.get('extent_raster',
                               [0, raster.shape[1], 0, raster.shape[0]])

    # Clipping raster
    clipped_array = clip_by_extent(raster,
                                   bbox,
                                   bbox_crs='EPSG:' + str(shape.crs.to_epsg()),
                                   save=save,
                                   path=path,
                                   extent_raster=extent_raster)

    return clipped_array
示例#3
0
def test_sample_interfaces_from_raster_points3(dem):
    from gemgis.raster import sample_interfaces
    from gemgis.utils import set_extent

    extent = set_extent(0, 972, 0, 1069)

    interfaces = sample_interfaces(raster=dem.read(1),
                                   extent=extent,
                                   point_x=[500, 600, 700],
                                   point_y=[500, 600, 700],
                                   formation='surface')

    assert isinstance(interfaces, pd.DataFrame)
    assert {'X', 'Y', 'Z', 'formation'}.issubset(interfaces.columns)
    assert len(interfaces) == 3
示例#4
0
def test_sample_orientations_from_raster_points3(dem):
    from gemgis.raster import sample_orientations
    from gemgis.utils import set_extent

    extent = set_extent(0, 972, 0, 1069)

    orientations = sample_orientations(raster=dem.read(1),
                                       extent=extent,
                                       point_x=[500, 600, 700],
                                       point_y=[500, 600, 700],
                                       formation='surface')

    assert isinstance(orientations, pd.DataFrame)
    assert {'X', 'Y', 'Z', 'formation', 'dip', 'azimuth', 'polarity'}.issubset(orientations.columns)
    assert len(orientations) == 3
示例#5
0
def clip_by_shape(gdf: gpd.geodataframe.GeoDataFrame,
                  shape: gpd.geodataframe.GeoDataFrame,
                  inplace: bool = False) -> gpd.geodataframe.GeoDataFrame:
    """
        Clipping vector data by extent
        Args:
            gdf: GeoDataFrame to be clipped
            shape: GeoDataFrame acting as bbox
            inplace: - bool - default False -> copy of the current gdf is created
        Return:
            gdf: GeoDataFrame with the clipped values
        """

    # Checking if the gdf is of type GeoDataFrame
    if not isinstance(gdf, gpd.geodataframe.GeoDataFrame):
        raise TypeError('gdf must be of type GeoDataFrame')

    # Checking if the shape is of type GeoDataFrame
    if not isinstance(shape, gpd.geodataframe.GeoDataFrame):
        raise TypeError('shape must be of type GeoDataFrame')

    # Checking if inplace is of type bool
    if not isinstance(inplace, bool):
        raise TypeError('Inplace must be of type bool')

    # Create deep copy of gdf
    if not inplace:
        gdf = gdf.copy(deep=True)

    # Setting the extent
    extent = set_extent(gdf=shape)

    # Clipping the gdf
    gdf = clip_by_extent(gdf, extent, inplace=inplace)

    return gdf
示例#6
0
def plot_data(geo_data,
              show_basemap: bool = False,
              show_geolmap: bool = False,
              show_topo: bool = False,
              show_interfaces: bool = False,
              show_orientations: bool = False,
              show_customsections: bool = False,
              show_wms: bool = False,
              show_legend: bool = True,
              show_hillshades: bool = False,
              show_slope: bool = False,
              show_aspect: bool = False,
              show_contours: bool = False,
              add_to_extent: float = 0,
              hide_topo_left: bool = False,
              **kwargs):
    """Plot Input Data
    Args:
        geo_data: GemPy Geo Data Class containing the raw data
        show_basemap: bool - showing the basemap
        show_geolmap: bool - showing the geological map
        show_topo: bool - showing the topography/digital elevation model
        show_interfaces: bool - showing the interfaces
        show_orientations: bool - showing orientations
        show_customsections: bool - showing custom sections
        show_wms: bool - showing a WMS layer
        show_legend: bool - showing the legend of interfaces
        show_hillshades: bool - showing hillshades
        show_slope: bool - showing the slope of the DEM
        show_aspect: bool - showing the aspect of the DEM
        show_contours: bool - showing the contours of the DEM
        add_to_extent: float - number of meters to add to the extent of the plot in each direction
        hide_topo_left: bool - if set to True, the topography will not be shown in the left plot
    Kwargs:
        cmap_basemap: str/cmap for basemap
        cmap_geolmap: str/cmap for geological map
        cmap_topo: str/cmap for topography
        cmap_hillshades: str/cmap for hillshades
        cmap_slope: str/cmap for slope
        cmap_aspect: str/cmap for aspect
        cmap_interfaces: str/cmap for interfaces
        cmap_orientations: str/cmap for orientations
        cmap_wms: str/cmap for WMS Service
        cmap_contours: str/cmap for contour lines
        """

    # Converting GeoDataFrame extent to list extent
    if isinstance(geo_data.extent, gpd.geodataframe.GeoDataFrame):
        geo_data.extent = set_extent(gdf=geo_data.extent)

    # Getting and checking kwargs
    cmap_basemap = kwargs.get('cmap_basemap', 'gray')

    if not isinstance(cmap_basemap, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    # Getting and checking kwargs
    cmap_geolmap = kwargs.get('cmap_geolmap', 'gray')

    if not isinstance(cmap_geolmap, (str, type(None), list)):
        raise TypeError('Colormap must be of type string')

    cmap_topo = kwargs.get('cmap_topo', 'gist_earth')

    if not isinstance(cmap_topo, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_contours = kwargs.get('cmap_contours', 'gist_earth')

    if not isinstance(cmap_contours, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_hillshades = kwargs.get('cmap_hillshades', 'gray')

    if not isinstance(cmap_hillshades, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_slope = kwargs.get('cmap_slope', 'RdYlBu_r')

    if not isinstance(cmap_slope, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_aspect = kwargs.get('cmap_aspect', 'twilight_shifted')

    if not isinstance(cmap_aspect, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_interfaces = kwargs.get('cmap_interfaces', 'gray')

    if not isinstance(cmap_interfaces, (list, str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_orientations = kwargs.get('cmap_orientations', 'gray')

    if not isinstance(cmap_orientations, (list, str, type(None))):
        raise TypeError('Colormap must be of type string')

    cmap_wms = kwargs.get('cmap_wms', None)

    if not isinstance(cmap_wms, (str, type(None))):
        raise TypeError('Colormap must be of type string')

    # Create figure and axes
    fig, (ax1, ax2) = plt.subplots(ncols=2,
                                   sharex='all',
                                   sharey='all',
                                   figsize=(20, 10))

    # Plot basemap
    if show_basemap:
        if not isinstance(geo_data.basemap, type(None)):
            ax1.imshow(np.flipud(geo_data.basemap),
                       origin='lower',
                       cmap=cmap_basemap,
                       extent=geo_data.extent[:4])

    # Plot geological map
    if show_geolmap:
        if isinstance(geo_data.geolmap, np.ndarray):
            ax1.imshow(np.flipud(geo_data.geolmap),
                       origin='lower',
                       cmap=cmap_geolmap,
                       extent=geo_data.extent[:4])
        else:
            geo_data.geolmap.plot(ax=ax1,
                                  column='formation',
                                  alpha=0.75,
                                  legend=True,
                                  cmap=ListedColormap(cmap_geolmap),
                                  aspect='equal')

    # Plot WMS Layer
    if show_wms:
        if not isinstance(geo_data.wms, type(None)):
            ax1.imshow(np.flipud(geo_data.wms),
                       origin='lower',
                       cmap=cmap_wms,
                       extent=geo_data.extent[:4])

    # Plot topography
    if show_topo:
        if not hide_topo_left:
            if not isinstance(geo_data.raw_dem, type(None)):
                if isinstance(geo_data.raw_dem, np.ndarray):
                    ax1.imshow(np.flipud(geo_data.raw_dem),
                               origin='lower',
                               cmap=cmap_topo,
                               extent=geo_data.extent[:4],
                               alpha=0.5)

    # Set labels, grid and limits
    ax1.set_xlabel('X')
    ax1.set_ylabel('Y')
    ax1.grid()
    ax1.set_ylim(geo_data.extent[2] - add_to_extent,
                 geo_data.extent[3] + add_to_extent)
    ax1.set_xlim(geo_data.extent[0] - add_to_extent,
                 geo_data.extent[1] + add_to_extent)

    # Plot basemap
    if show_basemap:
        if not isinstance(geo_data.basemap, type(None)):
            ax2.imshow(np.flipud(geo_data.basemap),
                       origin='lower',
                       cmap=cmap_basemap,
                       extent=geo_data.extent[:4])

    # Plot geolmap
    if show_geolmap:
        if isinstance(geo_data.geolmap, np.ndarray):
            ax2.imshow(np.flipud(geo_data.geolmap),
                       origin='lower',
                       cmap=cmap_geolmap,
                       extent=geo_data.extent[:4])
        else:
            geo_data.geolmap.plot(ax=ax2,
                                  column='formation',
                                  alpha=0.75,
                                  legend=True,
                                  cmap=ListedColormap(cmap_geolmap),
                                  aspect='equal')

    # Plot topography
    if show_topo:
        if not isinstance(geo_data.raw_dem, type(None)):
            if isinstance(geo_data.raw_dem, np.ndarray):
                ax2.imshow(np.flipud(geo_data.raw_dem),
                           origin='lower',
                           cmap=cmap_topo,
                           extent=geo_data.extent[:4],
                           alpha=0.5)
            else:
                geo_data.raw_dem.plot(ax=ax2,
                                      column='Z',
                                      legend=False,
                                      linewidth=5,
                                      cmap=cmap_topo,
                                      aspect='equal')

    # Plot contours
    if show_contours:
        if not isinstance(geo_data.contours, type(None)):
            geo_data.contours.plot(ax=ax2,
                                   column='Z',
                                   legend=False,
                                   linewidth=5,
                                   cmap=cmap_contours,
                                   aspect='equal')

    # Plot WMS Layer
    if show_wms:
        if not isinstance(geo_data.wms, type(None)):
            ax2.imshow(np.flipud(geo_data.wms),
                       origin='lower',
                       cmap=cmap_wms,
                       extent=geo_data.extent[:4])

    # Plot hillshades
    if show_hillshades:
        if not isinstance(geo_data.hillshades, type(None)):
            ax2.imshow(np.flipud(geo_data.hillshades),
                       origin='lower',
                       cmap=cmap_hillshades,
                       extent=geo_data.extent[:4])

    # Plot slope
    if show_slope:
        if not isinstance(geo_data.slope, type(None)):
            ax2.imshow(np.flipud(geo_data.slope),
                       origin='lower',
                       cmap=cmap_slope,
                       extent=geo_data.extent[:4])

    # Plot aspect
    if show_aspect:
        if not isinstance(geo_data.aspect, type(None)):
            ax2.imshow(np.flipud(geo_data.aspect),
                       origin='lower',
                       cmap=cmap_aspect,
                       extent=geo_data.extent[:4])

    # Plot interfaces and orientations
    if show_interfaces:

        if not isinstance(geo_data.raw_i, type(None)):
            if all(geo_data.raw_i.geom_type == 'Point'):
                geo_data.raw_i.plot(ax=ax2,
                                    column='formation',
                                    legend=show_legend,
                                    s=200,
                                    aspect='equal')
            elif all(geo_data.raw_i.geom_type == 'LineString'):
                geo_data.raw_i.plot(ax=ax2,
                                    column='formation',
                                    legend=show_legend,
                                    linewidth=5,
                                    cmap=cmap_interfaces,
                                    aspect='equal')
            else:
                if not cmap_interfaces:
                    geo_data.raw_i.plot(ax=ax2,
                                        column='formation',
                                        legend=show_legend,
                                        aspect='equal')
                else:
                    geo_data.raw_i.plot(ax=ax2,
                                        column='formation',
                                        legend=show_legend,
                                        cmap=ListedColormap(cmap_interfaces),
                                        aspect='equal')

    if show_orientations:
        if not isinstance(geo_data.raw_o, type(None)):
            geo_data.raw_o.plot(ax=ax2,
                                column='formation',
                                legend=True,
                                s=200,
                                aspect='equal',
                                cmap=cmap_orientations)

    # Plot custom sections
    if show_customsections:
        if not isinstance(geo_data.customsections, type(None)):
            geo_data.customsections.plot(ax=ax2,
                                         legend=show_legend,
                                         linewidth=5,
                                         color='red',
                                         aspect='equal')

    # Set labels, grid and limits
    ax2.set_xlabel('X')
    ax2.set_ylabel('Y')
    ax2.grid()
    ax2.set_ylim(geo_data.extent[2] - add_to_extent,
                 geo_data.extent[3] + add_to_extent)
    ax2.set_xlim(geo_data.extent[0] - add_to_extent,
                 geo_data.extent[1] + add_to_extent)

    return fig, ax1, ax2