Beispiel #1
0
 def set_polygon_layer(self, attr, layer_file, name="layer"):
     try:
         self.__setattr__(
             attr,
             PolygonLayer(layer_file,
                          name=name).clean_geometry(delete_invalid=True))
     except GeoLayerError:
         raise ConfigurationError("Invalid polygon layer file '%s'" %
                                  layer_file)
Beispiel #2
0
    def polygonize(self, field_name, layer_name="layer", is_8_connected=False):
        """ Convert raster into vector polygon(s)

        :param field_name: name of the corresponding field in the final shape file
        :param layer_name: name of resulting layer
        :param is_8_connected: pixel connectivity used for polygon
        :return:
        """
        check_type(is_8_connected, bool)
        with ShapeTempFile() as out_shp:
            self._gdal_polygonize(out_shp, layer_name, field_name, is_8_connected)
            return PolygonLayer(out_shp, name=layer_name)
Beispiel #3
0
    def table_to_layer(self, table_name, schema=None, geom_type=None, bounds=None, polygon_extent=None):
        """ Convert table from database to GeoLayer instance

        :param table_name: name of table (case sensitive)
        :param schema: database schema (case sensitive)
        :param geom_type: geometry type
        :param bounds: bounding box (x_min, y_min, x_max, y_max)
        :param polygon_extent: shapely polygon
        :return:
        """
        if schema is None:
            schema = "public"

        if bounds is not None and polygon_extent is None:
            sql_string = f'SELECT * FROM "{schema}"."{table_name}" WHERE "{schema}"."{table_name}".geom && ' \
                         f'ST_MakeEnvelope({bounds[0]}, {bounds[1]}, {bounds[2]}, {bounds[3]})'
        elif polygon_extent is not None and bounds is None:
            sql_string = f'SELECT * FROM "{schema}"."{table_name}" WHERE ST_Within("{schema}"."{table_name}".geom, ' \
                         f'{polygon_extent})'
        else:
            sql_string = f'SELECT * FROM "{schema}"."{table_name}"'

        df = GeoDataFrame.from_postgis(sql_string, self.engine)

        if table_name in self.get_table_names(schema) and geom_type is None:
            try:
                layer = PolygonLayer(df, name=table_name)
            except GeoLayerError:
                try:
                    layer = LineLayer(df, name=table_name)
                except GeoLayerError:
                    layer = PointLayer(df, name=table_name)
        elif table_name in self.get_table_names(schema) and geom_type is not None:
            try:
                geom_type = check_string(geom_type, ("point", "line", "polygon"))
            except ValueError:
                raise SpatialDatabaseError("Invalid geometry type '%s'. Must be 'point', 'line' or 'polygon'." %
                                           geom_type)
            layer = self.layer_class[geom_type](df, name=table_name)
        else:
            raise SpatialDatabaseError("No table named '%s' in database '%s'" % (table_name, self.db_name))

        return layer
Beispiel #4
0
    def get_osm_layers(self, tags, crs=None, **kwargs):
        """ Retrieve OSM layers used for addressing (admin levels, streets, etc.)

        :param tags: list of tag/values tuples (e.g.: [("admin_level", ("10","11")), ("highway")]
        :param crs: set either crs or epsg code
        :param kwargs: keyword arguments of "from_osm" GeoLayer method
        :return:
        """
        self._layers = []
        for tag in tags:

            if len(tag) == 1:
                key, val = tag[0], None
            else:
                key, val = tag[0], tag[1]

            if key == "highway":
                layer = LineLayer.from_osm(self._place, key, val, **kwargs)
            else:
                layer = PolygonLayer.from_osm(self._place, key, val, **kwargs)

            self._layers.append(layer.to_crs(crs=crs))

        return self
Beispiel #5
0
# -*- coding: utf-8 -*-
""" Module summary description.

More detailed description.
"""

# __all__ = []
# __version__ = '0.1'
__author__ = 'Benjamin Pillot'
__copyright__ = 'Copyright 2018, Benjamin Pillot'
__email__ = '*****@*****.**'

from gistools.layer import PolygonLayer

biomass = PolygonLayer(
    "/home/benjamin/ownCloud/Post-doc Guyane/GREECE model/Results/Biomass/generation.geojson"
)
solar_pv = PolygonLayer(
    "/home/benjamin/ownCloud/Post-doc Guyane/GREECE model/Results/Solar PV/result.geojson"
)

solar_pv["Polygon"] = ["PV %d" % n for n in range(len(solar_pv))]
solar_pv["Nature"] = ["PV"] * len(solar_pv)

area = biomass.attr_area(solar_pv, "Nature", normalized=True)
polygon = biomass.attr_area(solar_pv, "Polygon", normalized=True)

# print(area)
# print(len(biomass))
print(area['PV'])
print(polygon['PV 0'])
Beispiel #6
0
More detailed description.
"""

from gistools.layer import GeoLayer, PolygonLayer

# __all__ = []
# __version__ = '0.1'
from utils.sys.timer import Timer

__author__ = 'Benjamin Pillot'
__copyright__ = 'Copyright 2018, Benjamin Pillot'
__email__ = '*****@*****.**'

poly = "/home/benjamin/Documents/Post-doc Guyane/Data/Base lines_/flat_slope_layer.shp"
parc = "/home/benjamin/ownCloud/Post-doc Guyane/Data/Geo layers/Parc amazonien/enp_pn_s_973.shp"

slope_layer = PolygonLayer(poly)
with Timer() as t:
    slope_layer = slope_layer.explode()
print("explode time: %s" % t)

slope_layer.to_file(
    "/home/benjamin/Documents/Post-doc Guyane/Data/Base lines_/flat_slope_layer_explode_test.shp"
)

# amazonian_parc = GeoLayer(parc)
# amazonian_parc = amazonian_parc.explode()

# test = slope_layer.overlay(amazonian_parc, how="difference")
Beispiel #7
0
# -*- coding: utf-8 -*-
""" Compute statistics using ZonalStatistics

Compute average from raster cells within a polygon
"""

from gistools.stats import ZonalStatistics
from gistools.raster import RasterMap
from gistools.layer import PolygonLayer

# Create a digital elevation model from SRTM DEM of French Guiana
biomass = RasterMap("biomasse_ressource.tif", no_data_value=-9999)

# Import a geographical layer made of 6 large polygons from a shapefile
layer = PolygonLayer("enp_pn_s_973.shp")

# Convert DEM to layer's coordinate reference system
biomass = biomass.to_crs(layer.crs)

# Create ZonalStatistics instance from biomass and layer.
zonal_stat = ZonalStatistics(biomass,
                             layer,
                             is_surface_weighted=True,
                             all_touched=True)

# Compute slope average within each polygon
avg = zonal_stat.mean()
std = zonal_stat.std()
print(std)
print(avg)
Beispiel #8
0
                                nparts,
                                tpwgts=tpweights,
                                ubvec=None,
                                recursive=recursive,
                                **metis_options)
    partition = [[] for _ in range(nparts)]
    for u, i in zip(graph, parts):
        partition[i].append(u)

    # Only return non-empty parts
    return [part for part in partition if part]


if __name__ == "__main__":
    from matplotlib import pyplot
    from gistools.layer import PolygonLayer
    test = PolygonLayer(
        "/home/benjamin/Documents/PRO/PROJET_GREECE_OPSPV/001_DONNEES/data_greece"
        "/Geo layers/Parc amazonien/enp_pn_s_973.shp")
    # test = PolygonLayer("/home/benjamin/Desktop/APUREZA/geocoding/04_Codes/01_CodeSaoSeb/admin_level_10.shp")
    test = test.to_crs(epsg=32723)
    m = test.partition(100000000,
                       contig=True,
                       ncuts=50,
                       show_progressbar=True,
                       objtype="cut")

    m.plot()

    pyplot.show()
Beispiel #9
0
# -*- coding: utf-8 -*-
""" Split polygon into sub-polygons with equal area using graph partition (requires METIS packages)

More detailed description.
"""
import numpy as np
from matplotlib import pyplot as plt

from gistools.layer import PolygonLayer

test = PolygonLayer("enp_pn_s_973.shp")
test = test[[0]].to_crs(32622)
test = test.partition(50000000,
                      disaggregation_factor=20,
                      precision=100,
                      split_method="hexana",
                      contig=True,
                      ncuts=2)
test["attr"] = np.random.randint(1000, size=(len(test), ))

# Plot the resulting sub-polygons
test.plot(attribute="attr")
plt.show()

# Show corresponding areas
print(test.area)
Beispiel #10
0
# test = from_cgiar_online_database(bounds)
# test.to_file("/home/benjamin/srtm_corse.tif")

# test = DigitalElevationModel("/home/benjamin/dem_test.tif").clip((13, 42, 15, 45)).to_file(
#     "/home/benjamin/dem_clip_test.tif")
# pop = Raster("/home/benjamin/Documents/PRO/PRODUITS/POPULATION_DENSITY/001_DONNEES/COTE_D_IVOIRE"
#              "/population_civ_2019-07-01_geotiff/population_civ_2019-07-01.tif")
from pyrasta.tools.stats import _zonal_stats

dem = DigitalElevationModel(
    "/home/benjamin/Documents/PRO/PRODUITS/TESTS/dem_ci.tif")
test = dem.to_crs(32630).slope("degree")
test.to_file("/home/benjamin/dem_slope_ci.tif")

country = PolygonLayer.from_gpd(
    ox.geocode_to_gdf(
        dict(country="Cote d'Ivoire", admin_level=2,
             type="boundary"))).to_crs(32630).clean_geometry()

# dem = from_cgiar_online_database(country.total_bounds)
# dem.to_file("/home/benjamin/dem_ci.tif")

honeycomb = country.split(country.area[0] / 100,
                          method="hexana",
                          show_progressbar=True)

honeycomb = honeycomb.to_crs(dem.crs)
honeycomb.to_file("/home/benjamin/Documents/PRO/PRODUITS/TESTS/honeycomb.shp")
honeycomb["ID"] = honeycomb.index

# test = dem.clip(mask=honeycomb[[15]], all_touched=True)
# test.to_file("/home/benjamin/pop.tif")