How to use the shapely.geometry.MultiPoint 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 pyproj4 / pyproj / test / test_geod.py View on Github external
def test_geometry_area_perimeter__multipoint():
    geod = Geod(ellps="WGS84")
    assert geod.geometry_area_perimeter(
        MultiPoint([Point(1, 2), Point(3, 4), Point(5, 2)])
    ) == (0, 0)
github boschresearch / pcg_gazebo_pkgs / pcg_libraries / src / pcg_gazebo / generators / occupancy.py View on Github external
points = MultiPoint(locations)
                # Dilate points and add them to the occupied area
                footprint_areas.append(points.buffer(np.max([step_x, step_y])))
            PCG_ROOT_LOGGER.info('Vertical ray tracing done, model={}'.format(model_name))
            return footprint_areas

        x_samples = np.arange(x_limits[0], x_limits[1] + step_x, step_x)
        y_samples = np.arange(y_limits[0], y_limits[1] + step_y, step_y)

        if x_samples.shape[0] * y_samples.shape[0] > 1e5:        
            try:                
                # Extract only the unique point intersections
                ray_intersections = np.unique(ray_intersections, axis=0)                
                # Generating ray origins from the maximum Z level limit
                PCG_ROOT_LOGGER.info('Performing triangulation, model={}'.format(model_name))
                triangles = triangulate(MultiPoint(ray_intersections))
                PCG_ROOT_LOGGER.info('# triangles={}, model={}'.format(
                    len(triangles), model_name))

                # Filter out the triangles that belong to the mesh footprint
                max_z_level = np.max(z_levels)
                ray_origins = np.array([[t.centroid.xy[0][0], t.centroid.xy[1][0], max_z_level] for t in triangles])
                ray_directions = np.array([[0, 0, -1] for _ in range(ray_origins.shape[0])])

                idx = None
                PCG_ROOT_LOGGER.info('Checking triangles centroids for intersections with mesh, model={}'.format(model_name))
                for mesh in meshes:
                    locations, index_ray, index_tri = mesh.ray.intersects_location(
                        ray_origins=ray_origins,
                        ray_directions=ray_directions,
                        multiple_hits=False)
github aleju / imgaug / imgaug / augmentables / polys.py View on Github external
if len(self.exterior) in [1, 2]:
            ls = self.to_line_string(closed=False)
            ls_clipped = ls.clip_out_of_image(image)
            assert len(ls_clipped) <= 1
            if len(ls_clipped) == 0:
                return []
            return [self.deepcopy(exterior=ls_clipped[0].coords)]

        h, w = image.shape[0:2] if ia.is_np_array(image) else image[0:2]
        poly_shapely = self.to_shapely_polygon()
        poly_image = shapely.geometry.Polygon([(0, 0), (w, 0), (w, h), (0, h)])
        multipoly_inter_shapely = poly_shapely.intersection(poly_image)
        ignore_types = (shapely.geometry.LineString,
                        shapely.geometry.MultiLineString,
                        shapely.geometry.point.Point,
                        shapely.geometry.MultiPoint)
        if isinstance(multipoly_inter_shapely, shapely.geometry.Polygon):
            multipoly_inter_shapely = shapely.geometry.MultiPolygon(
                [multipoly_inter_shapely])
        elif isinstance(multipoly_inter_shapely,
                        shapely.geometry.MultiPolygon):
            # we got a multipolygon from shapely, no need to change anything
            # anymore
            pass
        elif isinstance(multipoly_inter_shapely, ignore_types):
            # polygons that become (one or more) lines/points after clipping
            # are here ignored
            multipoly_inter_shapely = shapely.geometry.MultiPolygon([])
        elif isinstance(multipoly_inter_shapely,
                        shapely.geometry.GeometryCollection):
            # Shapely returns GEOMETRYCOLLECTION EMPTY if there is nothing
            # remaining after the clip.
github Wireless-Innovation-Forum / Spectrum-Access-System / src / harness / reference_models / tools / entities.py View on Github external
template_cbsd: A |Cbsd| used as a template.
    polygon: A |shapely.Polygon| where to put the Cbsd.
    nlcd_driver: The land cover driver for detecting inland positions (optional).
    urban_areas: An optional  |shapely.MultiPolygon| defining the urban areas.
      If not specified, do not enforce the Cbsd to be in urban areas.
  """
  t = template_cbsd
  bounds = polygon.bounds
  cbsds = []
  total_asked, total_got = 0, 0
  ratio = 0.5
  while len(cbsds) < num_cbsds:
    n_block = int((num_cbsds - len(cbsds)) / ratio * 1.2)
    lngs = np.random.uniform(bounds[0], bounds[2], n_block)
    lats = np.random.uniform(bounds[1], bounds[3], n_block)
    in_points = sgeo.MultiPoint(zip(lngs, lats))
    in_points = polygon.intersection(in_points)
    if urban_areas is not None:
      in_points = urban_areas.intersection(in_points)
    if isinstance(in_points, sgeo.Point):
      in_points = [in_points]
    total_asked += n_block
    total_got += len(in_points)
    if not in_points:
      continue
    ratio = total_got / float(total_asked)
    for point in in_points:
      if len(cbsds) > num_cbsds: break
      if nlcd_driver is not None:
        land_cover = nlcd_driver.GetLandCoverCodes(point.y, point.x)
        if land_cover < nlcd.LandCoverCodes.PERENNIAL_SNOW:
          continue
github bellockk / alphashape / alphashape / alphashape.py View on Github external
Returns:

        ``shapely.geometry.Polygon`` or ``shapely.geometry.LineString`` or
        ``shapely.geometry.Point`` or ``geopandas.GeoDataFrame``: the resulting
            geometry
    """
    # If given a geodataframe, extract the geometry
    if USE_GP and isinstance(points, geopandas.GeoDataFrame):
        crs = points.crs
        points = points['geometry']
    else:
        crs = None

    if not isinstance(points, MultiPoint):
        points = MultiPoint(list(points))

    # If given a triangle for input, or an alpha value of zero or less,
    # return the convex hull.
    if len(points) < 4 or (alpha is not None and alpha <= 0):
        result = points.convex_hull
        if crs:
            gdf = geopandas.GeoDataFrame(geopandas.GeoSeries(result)).rename(
                columns={0: 'geometry'}).set_geometry('geometry')
            gdf.crs = crs
            return gdf
        else:
            return result

    # Determine alpha parameter if one is not given
    if alpha is None:
        try:
github philippkraft / cmf / pyCMF / src / cmf / geos_shapereader.py View on Github external
obj=None
        if type==0: # Null shape
            pass
        elif type==1: # Point 
            x,y=self.__readfmt('
github jeremylow / himawari_bot / himawari_hires.py View on Github external
POINTS = [
    # Clockwise from leftmost/higher middle ... one ?
    # Point being, we don't want to start somewhere way out in space,
    # because that is not interesting for this application.
    (0, 4275),
    (1225, 5500),
    (3500, 5500),
    (4220, 4970),
    (4220, 2025),
    (3000, 732),
    (1140, 732),
    (0, 1500)
]

# Polygon delimiting the 'interesting' parts of the Earth.
EARTH_POLYGON = MultiPoint(POINTS).convex_hull


def get_start_coord():
    """
    Get a top-left point to start our downward-rightward crop that
    is inside the Earth polygon

    Returns:
        coordinate tuple (0, 0 being top, left)
    """
    logger.info("Getting coordinates")
    while True:
        try_point = Point(random.randint(1, 4219), random.randint(732, 5499))
        if try_point.within(EARTH_POLYGON):
            break
        else:
github jeremylow / himawari_bot / himawari_giffer.py View on Github external
POINTS = [
    # Clockwise from leftmost/higher middle ... one ?
    # Point being, we don't want to start somewhere way out in space,
    # because that is not interesting for this application.
    (0, 4275),
    (1225, 5500),
    (3500, 5500),
    (4220, 4970),
    (4220, 2025),
    (3000, 732),
    (1140, 732),
    (0, 1500)
]

# Polygon delimiting the 'interesting' parts of the Earth.
EARTH_POLYGON = MultiPoint(POINTS).convex_hull


def _get_start_coord():
    """
    Get a top-left point to start our downward-rightward crop that
    is inside the Earth polygon

    Returns:
        coordinate tuple (0,0 being top-left)
    """
    while True:
        p = Point(random.randint(1, 4219), random.randint(732, 5499))
        if p.within(EARTH_POLYGON):
            # When returning the Y Coordinate, need to reverse axis,
            # since Shapely counts up from bottom right and PIL counts
            # down from top left.
github eclipse / sumo / tools / contributed / sumopy / plugins / mapmatching / mapmatching-10-preresults.py View on Github external
else:
            print 'DISCONNECTED: last matched edge', ids_edge[-1], ' did not reach final edges', ids_edge_final
            is_connected = False

        # check dist error
        inds_point = xrange(ind_point_initial, ind_point_final)
        n_points = len(inds_point)

        if (n_points >= 2) & (len(route) > 0):
            # print '  initialize distance error measurement',len(route)
            dist_points_tot = 0.0
            routestring = get_routelinestring(route, edges)
            # print '  routestring =',routestring

            # print '  coords',coords[inds_point].tolist()
            tracepoints = MultiPoint(coords[inds_point].tolist())

            # measure precision
            #routeset = set(route)
            #n_points_boundary = 0
            ind_tracepoint = 0
            for ind_point in inds_point:  # xrange(n_points):
                d = routestring.distance(tracepoints[ind_tracepoint])
                dist_points_tot += d
                # print '   v distance measurement',d,tracepoints[ind_tracepoint],coords[ind_point]#,n_points#,n_points_eff

                ind_tracepoint += 1

            err_dist = dist_points_tot/float(n_points)

        # print '  check',(lengthindex= self.lengthindex_min),(duration_gps>self.duration_min),(length_route>self.dist_min),(len(route)>0)
        # print '   twice',(lengthindex= self.lengthindex_min)&(duration_gps>self.duration_min)&(length_route>self.dist_min)&(len(route)>0)
github mdiener21 / python-geospatial-analysis-cookbook / ch09 / code / ch09-02_point_covers_line_endpoint.py View on Github external
'''
    list_end_nodes = []
    list_start_nodes = []

    for line in lines:
        coords = list(line.coords)

        line_start_point = Point(coords[0])
        line_end_point = Point(coords[-1])

        list_start_nodes.append(line_start_point)
        list_end_nodes.append(line_end_point)

    all_nodes = list_end_nodes + list_start_nodes

    return MultiPoint(all_nodes)