How to use the shapely.geometry.shape function in shapely

To help you get started, we’ve selected a few shapely examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nismod / digital_comms / scripts / fixed_preprocess.py View on Github external
def intersect_lad_areas_and_exchanges(exchanges, areas):

    exchange_to_lad_area_lut = defaultdict(list)

    idx = index.Index()
    [idx.insert(0, shape(exchange['geometry']).bounds, exchange) for exchange in exchanges]

    for area in areas:
        for n in idx.intersection((shape(area['geometry']).bounds), objects=True):
            area_shape = shape(area['geometry'])
            exchange_shape = shape(n.object['geometry'])
            if area_shape.intersects(exchange_shape):
                exchange_to_lad_area_lut[n.object['properties']['id']].append({
                    'lad': area['properties']['name'],
                    })

    return exchange_to_lad_area_lut
github DHI-GRAS / terracotta / terracotta / drivers / raster_base.py View on Github external
block_data = dataset.read(1, window=w, masked=True)

            # handle NaNs for float rasters
            block_data = np.ma.masked_invalid(block_data, copy=False)

            total_count += int(block_data.size)
            valid_data = block_data.compressed()

            if valid_data.size == 0:
                continue

            valid_data_count += int(valid_data.size)

            if np.any(block_data.mask):
                hull_candidates = RasterDriver._hull_candidate_mask(~block_data.mask)
                hull_shapes = [geometry.shape(s) for s, _ in features.shapes(
                    np.ones(hull_candidates.shape, 'uint8'),
                    mask=hull_candidates,
                    transform=windows.transform(w, dataset.transform)
                )]
            else:
                w, s, e, n = windows.bounds(w, dataset.transform)
                hull_shapes = [geometry.Polygon([(w, s), (e, s), (e, n), (w, n)])]
            convex_hull = geometry.MultiPolygon([convex_hull, *hull_shapes]).convex_hull

            tdigest.update(valid_data)
            sstats.update(valid_data)

        if sstats.count() == 0:
            return None

        convex_hull_wgs = warp.transform_geom(
github DigitalGlobe / gbdxtools / gbdxtools / images / ipe_image.py View on Github external
def _parse_geoms(self, **kwargs):
        """ Finds supported geometry types, parses them and returns the bbox """
        bbox = kwargs.get('bbox', None)
        wkt = kwargs.get('wkt', None)
        geojson = kwargs.get('geojson', None)
        bounds = None
        if bbox is not None:
            bounds = bbox
        elif wkt is not None:
            bounds = loads(wkt).bounds
        elif geojson is not None:
            bounds = shape(geojson).bounds
        return self._project_bounds(bounds)
github ungarj / mapchete / mapchete / io / _geometry_operations.py View on Github external
def to_shape(geom):
    """
    Convert geometry to shapely geometry if necessary.

    Parameters
    ----------
    geom : shapely geometry or GeoJSON mapping

    Returns
    -------
    shapely geometry
    """
    return shape(geom) if isinstance(geom, dict) else geom
github ungarj / mapchete / tools / generalize.py View on Github external
TileMatrixNSSize = float(round(TileMatrixTop - TileMatrixBottom, ROUND))

    TileNumbers = tile_numbers(zoom)

    TileNSSize = float(round(TileMatrixNSSize/TileNumbers[1], ROUND))
    TileWESize = float(round(TileMatrixWESize/TileNumbers[0], ROUND))

    TileMatrix = (TileMatrixLeft, TileMatrixTop, TileMatrixRight,
        TileMatrixBottom, TileMatrixWESize, TileMatrixNSSize, TileNSSize,
        TileWESize, TileNumbers)


    with fiona.open(input_file) as input_shape:
        geoms = []
        for feature in input_shape:
            geoms.append(shape(feature['geometry']))
        union_geometry = cascaded_union(geoms)

        # write WMTS tiles
        outtiles_schema = {
            'geometry': 'Polygon',
            'properties': {'column': 'str', 'row': 'str'},
        }
        with fiona.open(outtiles, 'w', 'GeoJSON', outtiles_schema) as sink:
            tiles = get_tiles(TileMatrix, union_geometry, parsed)
            for tile in tiles:
                col, row = tile
                feature = {}
                feature['properties'] = {}
                feature['properties']['column'] = col
                feature['properties']['row'] = row
                tilegeom = get_boundaries(TileMatrix, col, row)
github Geosyntec / pygridtools / pygridtools / validate.py View on Github external
def _explode_geom(row):
    # save each geo part in its own row
    gsr = geopandas.GeoSeries([
        poly for poly in geometry.shape(row['geometry'])
    ])
    meta = row['properties']
    return geopandas.GeoDataFrame(meta, geometry=gsr, index=gsr.index)
github Corvince / mesa-geo / mesa_geo / shapes.py View on Github external
For Geometry returns only the shape
    For GeometryCollection return a list of shapes
    For Feature return the shape and the properties members
    For FeatureCollection return a list of shapes and a list of properties
    members.
    """
    gj = GeoJSON
    geometries = ["Point", "MultiPoint", "LineString",
                  "MultiLineString", "Polygon", "MultiPolygon"]
    if gj['type'] in geometries:
        return shape(gj)

    if gj['type'] == 'GeometryCollection':
        shapes = []
        for geometry in gj['geometries']:
            shapes.append(shape(geometry))
        return shapes

    if gj['type'] == 'Feature':
        attributes = gj['properties']
        return shape(gj['geometry']), attributes

    if gj['type'] == "FeatureCollection":
        shapes, attributes = ([], [])
        for feature in gj['features']:
            shapes.append(shape(feature['geometry']))
            attributes.append(feature['properties'])
        return shapes, attributes
github nismod / digital_comms / scripts / network_preprocess_simplify_inputs.py View on Github external
def intersect_pcd_areas_and_exchanges(exchanges, areas):

    exchange_to_pcd_area_lut = defaultdict(list)

    # Initialze Rtree
    idx = index.Index()
    [idx.insert(0, shape(exchange['geometry']).bounds, exchange) for exchange in exchanges]

    for area in areas:
        for n in idx.intersection((shape(area['geometry']).bounds), objects=True):
            area_shape = shape(area['geometry'])
            exchange_shape = shape(n.object['geometry'])
            if area_shape.intersects(exchange_shape):
                exchange_to_pcd_area_lut[n.object['properties']['id']].append({
                    'postcode_area': area['properties']['postcode_a'],
                    })

    return exchange_to_pcd_area_lut
github openstreams / wflow / wflow-py / Scripts / wtools_py / modelbuilder.py View on Github external
polytypes = ("Polygon", "MultiPolygon")
    if region_filter == "region":
        # these polygon checks should cover all types of GeoJSON
        if d.type == "FeatureCollection":
            # this should check all features
            gtype = d.features[0].geometry.type
            if gtype not in polytypes:
                raise ValueError(
                    "Geometry type in {} is {}, needs to be a polygon".format(
                        path_geojson, gtype
                    )
                )
            # combine features into 1 geometry
            polys = []
            for fcatch in d.features:
                g = sg.shape(fcatch["geometry"])
                polys.append(g)
            # now simplify it to a rectangular polygon
            bnds = unary_union(polys).bounds
            geom = sg.mapping(sg.box(*bnds))
        elif d.type == "Feature":
            assert d.geometry.type in polytypes
            geom = d.geometry
        else:
            assert d.type in polytypes
            geom = d
        # now simplify it to a rectangular polygon
        bnds = sg.shape(geom).bounds
        geom = sg.mapping(sg.box(*bnds))
    else:
        if d.type == "FeatureCollection":
            nfeatures = len(d.features)