def convert_to_canonical(P=[]):
    """Convertion function to convert from shapely object to canonical form.

    Args:
        P: Shapely object representing a polygon.

    Returns:
        poly: A polygon represented in canonical form. [] otherwise.
    """

    if type(P) is not Polygon:
        logger.warn("Polygon conversion requested but wrong input specified.")
        return None

    poly = [[], []]

    if not LinearRing(P.exterior.coords).is_ccw:
        poly[0] = list(P.exterior.coords)[::-1][:-1]
    else:
        poly[0] = list(P.exterior.coords)[:-1]

    for hole in P.interiors:

        if LinearRing(hole.coords).is_ccw:
            poly[1].append(list(hole.coords)[::-1][:-1])
        else:
            poly[1].append(list(hole.coords)[:-1])

    return poly
Example #2
0
 def __call__(self) -> gpd.GeoDataFrame:
     tri = self._grd.elements.triangulation
     idxs = np.vstack(list(np.where(tri.neighbors == -1))).T
     boundary_edges = []
     for i, j in idxs:
         boundary_edges.append(
             (tri.triangles[i, j], tri.triangles[i, (j+1) % 3]))
     sorted_rings = sort_rings(edges_to_rings(boundary_edges),
                               self._grd.nodes.coord)
     data = []
     for bnd_id, rings in sorted_rings.items():
         coords = self._grd.nodes.coord[rings['exterior'][:, 0], :]
         geometry = LinearRing(coords)
         data.append({
                 "geometry": geometry,
                 "bnd_id": bnd_id,
                 "type": 'exterior'
             })
         for interior in rings['interiors']:
             coords = self._grd.nodes.coord[interior[:, 0], :]
             geometry = LinearRing(coords)
             data.append({
                 "geometry": geometry,
                 "bnd_id": bnd_id,
                 "type": 'interior'
             })
     return gpd.GeoDataFrame(data, crs=self._grd.crs)
Example #3
0
    def hit(self, car):
        print('??')
        x = car.position.x * 32
        y = car.position.y * 32
        print(x, y)
        lenght = car.length

        line1 = LineString([(x - lenght, y - lenght), (x + lenght, y - lenght),
                            (x - lenght, y + lenght),
                            (x + lenght, y + lenght)])
        line2 = LinearRing(self.inner_line)
        line3 = LinearRing(self.outer_line)

        intersection1 = (line1.intersection(line2))
        intersection2 = (line1.intersection(line3))

        if (isinstance(intersection1, shapely.geometry.multipoint.MultiPoint)):
            intersection1 = intersection1[len(intersection1) - 1]

        if (isinstance(intersection2, shapely.geometry.multipoint.MultiPoint)):
            intersection2 = intersection2[len(intersection2) - 1]

        if (len(intersection1.coords) > 0):
            return True

        if (len(intersection2.coords) > 0):
            return True

        return False
Example #4
0
    def find_linerings(self):
        if self.linerings_found:
            return
        # t = MapTools()
        firstpoint = self.lines[0][0]
        points = []
        previousEnd = firstpoint[1]
        #print("First point:",firstpoint)
        self.linerings_found = True
        for line in self.lines:
            # print (line[0],line[1],line[0]==previousEnd,end='')
            if points == [] or (line[0] == previousEnd).all():
                points.append(line[1])
            else:
                ring = Polygon(LinearRing(points))
                #print("Ring length:",len(ring.coords))
                #pyglet.graphics.draw(len(ring.coords), pyglet.gl.GL_LINE_LOOP,ring)
                self.linerings.append(ring)
                #self.plot(ring)
                #print(ring)
                points = []

            previousEnd = line[1]

        road = self.linerings[0].difference(self.linerings[1])
        self.road = road

        #object.intersects(other)
        #Returns True if the boundary or interior of the object intersect in any way with those of the other.

        if points != []:
            ring = Polygon(LinearRing(points))
            self.linerings.append(ring)
Example #5
0
def normalise_compound_region(compound_region_indices, regions):
    '''Normalise a compound region so that exterior contours are
  counterclockwise and holes are clockwise.
  '''
    _, sub_regions = compound_region_indices

    reference_orientation = LinearRing(regions[sub_regions[0]][1]).is_ccw
    reference_orientation_is_hole = is_reference_orientation_a_hole(
        regions, sub_regions)

    normalised_compound_region = []
    for sub_region in sub_regions:
        name, region, child_number = regions[sub_region]
        oriented_as_reference = LinearRing(
            region).is_ccw == reference_orientation
        is_hole = (oriented_as_reference if reference_orientation_is_hole else
                   (not oriented_as_reference))

        normalised_region = region.copy()
        if is_hole and LinearRing(region).is_ccw:
            normalised_region = np.flip(region, axis=0)
        if not is_hole and not LinearRing(region).is_ccw:
            normalised_region = np.flip(region, axis=0)
        normalised_compound_region.append(
            [name, normalised_region, child_number])
    return normalised_compound_region
Example #6
0
def flatten_geometry(geometry: BaseGeometry) -> BaseGeometry:
    """
    :param geometry: Shapely geometry object
    :return: geometry with Z values removed
    """

    geometry_type = type(geometry)

    # strip 3rd dimension
    if 'POLYGON Z' in geometry.wkt:
        polygons = ([polygon for polygon in geometry]
                    if geometry_type is MultiPolygon else [geometry])
        for polygon_index, polygon in enumerate(polygons):
            exterior_2d = LinearRing(
                [vertex[:2] for vertex in polygon.exterior.coords])
            interiors_2d = [
                LinearRing([vertex[:2] for vertex in interior.coords])
                for interior in polygon.interiors
            ]
            polygons[polygon_index] = Polygon(exterior_2d, interiors_2d)
        geometry = (MultiPolygon(polygons)
                    if geometry_type is MultiPolygon else Polygon(polygons[0]))

    if not geometry.is_valid:
        geometry = geometry.buffer(0)
    return geometry
Example #7
0
    def __init__(self, raster_mask, no_data_value=None, ignore_labels=None):
        if ignore_labels is None:
            ignore_labels = []

        self.geometries = [{
            'label':
            int(label),
            'polygon':
            Polygon(LinearRing(shp['coordinates'][0]),
                    [LinearRing(pts) for pts in shp['coordinates'][1:]])
        } for index, (shp, label) in enumerate(
            rasterio.features.shapes(raster_mask, mask=None))
                           if (int(label) is not no_data_value) and (
                               int(label) not in ignore_labels)]

        self.areas = np.asarray(
            [entry['polygon'].area for entry in self.geometries])
        self.decomposition = [
            shapely.ops.triangulate(entry['polygon'])
            for entry in self.geometries
        ]

        self.label2cc = collections.defaultdict(list)
        for index, entry in enumerate(self.geometries):
            self.label2cc[entry['label']].append(index)
Example #8
0
def findClosestStreet(pnt, streets, bld, sg=None):
    """
    :param pnt: point to check closest street to
    :param streets: all streets in dataset
    :param bld: building to be checked against intersection with street
    :return: Tuple containing line length, street, street index and the LineString itself
    """
    mylist = []
    for i, street in enumerate(streets):
        if not sg:
            if bld.geom.intersects(street):
                continue
            pol_ext = LinearRing(street.exterior.coords)
            d = pol_ext.project(pnt)
            p = pol_ext.interpolate(d)
            clstpnt = list(p.coords)[0]
            nline = LineString([pnt, clstpnt])
            mylist.append([nline.length, street, i, nline])
        else:
            pol_ext = LinearRing(streets[sg].exterior.coords)
            d = pol_ext.project(pnt)
            p = pol_ext.interpolate(d)
            clstpnt = list(p.coords)[0]
            nline = LineString([pnt, clstpnt])
            return [nline.length, streets[sg], sg, nline]

    smallest = min(mylist)
    return smallest
Example #9
0
def test_linearring_from_coordinate_sequence():
    expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]

    ring = LinearRing(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0)))
    assert ring.coords[:] == expected_coords

    ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)])
    assert ring.coords[:] == expected_coords
    def check_collision(self, car_point):
        car = LinearRing(car_point)
        outer = LinearRing(self.pointlist_out)
        inner = LinearRing(self.pointlist_in)

        if outer.intersects(car) or inner.intersects(car):
            return True
        else:
            return False
Example #11
0
def test_linearring_from_empty():
    ring = LinearRing()
    assert ring.is_empty
    assert isinstance(ring.coords, CoordinateSequence)
    assert ring.coords[:] == []

    ring = LinearRing([])
    assert ring.is_empty
    assert isinstance(ring.coords, CoordinateSequence)
    assert ring.coords[:] == []
Example #12
0
def _resample_outer_and_inner_polygons(outer_polygon, inner_polygon, nodeinterval):
    # resample inner and outer polygons
    outer = LinearRing(outer_polygon)
    inner = LinearRing(inner_polygon)
    samples = int(outer.length/nodeinterval+0.5)
    outer_res = np.zeros((samples,2))
    inner_res = np.zeros((samples,2))
    for i in range(samples):
        outer_res[i,:] = outer.interpolate(i/samples, normalized=True)
        inner_res[i,:] = inner.interpolate(i/samples, normalized=True)
    return outer_res, inner_res
Example #13
0
def get_lines(shape, gap):
    hlines = get_hlines(shape, gap)
    lines, hlines_by_heights = get_intersections(shape, hlines)
    connection_lines = LinearRing(shape.exterior).difference(MultiLineString(hlines))
    connection_lines = geom_to_list(connection_lines)
    for hole in shape.interiors:
        extra_connection_lines = LinearRing(hole).difference(MultiLineString(hlines))
        extra_connection_lines = geom_to_list(extra_connection_lines)
        connection_lines.extend(extra_connection_lines)
    connection_lines = remove_same_height_lines(lines, connection_lines)
    return lines, connection_lines, hlines_by_heights
def mock_geocoder() -> 'MockGeocoder':
    point_gdf = geo_data_frame([Point(-5, 17)])
    point_dict = {'coord': ['{"type": "Point", "coordinates": [-5.0, 17.0]}']}

    polygon_gdf = geo_data_frame(MultiPolygon([
        Polygon(LinearRing([(11, 12), (13, 14), (15, 13), (7, 4)])),
        Polygon(LinearRing([(10, 2), (13, 10), (12, 3)]))
    ])
    )

    polygon_dict = {
        'coord': [
            '{"type": "Polygon", "coordinates": [[[11.0, 12.0], [13.0, 14.0], [15.0, 13.0], [7.0, 4.0], [11.0, 12.0]]]}',
            '{"type": "Polygon", "coordinates": [[[10.0, 2.0], [13.0, 10.0], [12.0, 3.0], [10.0, 2.0]]]}'
        ]
    }

    class MockGeocoder(Geocoder):
        def __init__(self):
            self._get_geocodes_invoked = False
            self._limits_fetched = False
            self._centroids_fetched = False
            self._boundaries_fetched = False

        def get_test_point_dict(self):
            return point_dict

        def get_test_polygon_dict(self):
            return polygon_dict

        def get_test_geocodes(self) -> dict:
            return {'request': ['foo'], 'found name': ['FOO']}

        def get_geocodes(self):
            self._get_geocodes_invoked = True
            return DataFrame(self.get_test_geocodes())

        def get_limits(self) -> GeoDataFrame:
            self._limits_fetched = True
            return polygon_gdf

        def get_centroids(self) -> GeoDataFrame:
            self._centroids_fetched = True
            return point_gdf

        def get_boundaries(self, resolution=None) -> GeoDataFrame:
            self._boundaries_fetched = True
            return polygon_gdf

        def assert_get_geocodes_invocation(self):
            assert self._get_geocodes_invoked, 'to_data_frame() invocation expected, but not happened'

    return MockGeocoder()
Example #15
0
def plot_push_results(pushes, poses):
    bins = np.arange(-0.5125, 0.5375, 0.025)
    target_angles = np.arange(-0.5, 0.525, 0.025)
    bin_map = np.digitize([push.angle for push in pushes], bins)
    candidates = [[a, [], []] for a in target_angles]
    for i, (push, pose) in enumerate(zip(pushes, poses)):
        d = bin_map[i] - 1
        ta = target_angles[d]
        candidates[d][1].append(push)
        candidates[d][2].append(pose)
        #if((candidates[d][1] is None) or abs(push.angle - ta) < abs(candidates[d][1].angle - ta)):
        #    candidates[d] = [ta, push, pose]


    t_boxes = []
    for c in candidates:
        target_angle = c[0]
        c_pushes = c[1]
        c_poses = c[2]
        if len(c_poses) > 0:

            x = np.median([p.position.x for p in c_poses])
            y = np.median([p.position.y for p in c_poses])

            push_angle = np.median([p.angle for p in c_pushes])
            push_x = np.median([p.approach.position.x for p in c_pushes])
            push_y = np.median([p.approach.position.y for p in c_pushes])

            yaw = np.median(np.array([get_yaw(p) for p in c_poses]))
            cos_a = math.cos(yaw)
            sin_a = math.sin(yaw)

            transformed_box = affinity.affine_transform(get_box(0.162, 0.23), [cos_a, -sin_a, sin_a, cos_a, x, y])
            push_line = get_line(push_x, push_y, c_pushes[0].distance - 0.004, push_angle + get_yaw(push.approach))
            t_boxes.append((target_angle, transformed_box, push_line))
        

    box = get_box(0.162, 0.23)
    #x, y = box.xy
    y, x = LinearRing(box.exterior.coords).xy
    plt.plot(x, y, color="black", linewidth=3)

    for angle, box, push_line in t_boxes:
        y, x = LinearRing(box.exterior.coords).xy
        plt.plot(x, y)
        y,x = push_line.xy
        plt.plot(x, y)
        

    plt.xlim(-0.2, 0.2)
    plt.ylim(-0.2, 0.2)
    plt.axes().set_aspect('equal', adjustable='box')
    plt.show()
Example #16
0
    def __generate_visivility_graph(self):
        def extend_line(line):
            return np.append(line, [line[0], line[1]], axis=0)

        H = self.__H
        join_style = JOIN_STYLE.mitre

        is_ccw = LinearRing(self.borders_points).is_ccw
        map_po = LineString(extend_line(self.borders_points)).parallel_offset(
            H,
            'left' if is_ccw else 'right',
            join_style=join_style
        )
        if map_po.geom_type == 'MultiLineString':
            geoms = list(map_po.geoms)
            map_po = list(chain(geoms[0].coords, geoms[1].coords))

        self.__support_points = np.array(map_po)
        self.__holes = []

        for item in self.items_border_points:
            if item.size > 0:
                is_ccw = LinearRing(item).is_ccw
                item_po = LineString(extend_line(item)).parallel_offset(
                    H,
                    'right' if is_ccw else 'left',
                    join_style=join_style
                )
                if item_po.geom_type == 'MultiLineString':
                    geoms = list(item_po.geoms)
                    item_po = list(chain(geoms[0].coords, geoms[1].coords))
                support_item_points = np.array(item_po)
                self.__holes.append(support_item_points)

        all_points = self.__support_points

        for hole in self.__holes:
            all_points = np.append(all_points, hole, axis=0)

        holes_p = [Polygon(h) for h in self.__holes]
        border_p = Polygon(self.__support_points)

        points_len = len(all_points)
        visibility_graph = np.zeros(shape=(points_len, points_len))

        for i in range(all_points.shape[0]):
            for j in range(all_points.shape[0]):

                line = np.array((all_points[i], all_points[j]))
                if self.is_valid(LineString(line), border_p, holes_p):
                    visibility_graph[i, j] = True

        return all_points, visibility_graph
Example #17
0
def has_collision(P, edge):

	exterior = LinearRing(P[0])
	holes = P[1]
	segment = LineString(edge)

	if exterior.intersects(segment): return True

	for hole in holes:
		interior = LinearRing(hole)
		if interior.intersects(segment): return True
	return False
Example #18
0
    def screen_building(self, building):
        building_polyline = LinearRing(list(building.exterior.coords))
        points = [self.point.coords[0]]
        angles = np.linspace(-VIEWING_ANGLE / 2, VIEWING_ANGLE / 2,
                             VIEWING_POINTS)
        is_sector_screened = False
        for angle in angles:
            v = rotate(self.center,
                       angle,
                       origin=self.center.coords[0],
                       use_radians=False)
            intersection = building_polyline.intersection(v)
            if isinstance(intersection, Point):
                if intersection.distance(self.point) < ALLOWED_DISTANCE_ERROR:
                    # Camera is placed on this building.
                    points.append(v.coords[1])
                    continue
                points.append((intersection.x, intersection.y))
                is_sector_screened = True
            elif isinstance(intersection, LineString):
                lines = [
                    LineString([(self.point.x, self.point.y), p])
                    for p in list(intersection.coords)
                ]
                line = min(lines, key=lambda l: l.length)
                points.append(line.coords[1])
                is_sector_screened = True
            elif len(list(intersection)) > 1:
                pts = []
                for entity in intersection:
                    if isinstance(entity, Point):
                        pts.append(entity)
                    elif isinstance(entity, LineString):
                        for pt in entity.coords:
                            pts.append(Point(pt))
                    else:
                        continue
                lines = [
                    LineString([(self.point.x, self.point.y), (p.x, p.y)])
                    for p in pts
                ]
                line = min(lines, key=lambda l: l.length)
                points.append(line.coords[1])
                is_sector_screened = True
            else:
                points.append(v.coords[1])

        if not is_sector_screened:
            return

        self.polyline = LinearRing(points)
        self.polygon = Polygon(points)
Example #19
0
def segmentize_geometry(geometry, segmentize_value):
    """
    Segmentize Polygon outer ring by segmentize value.

    Just Polygon geometry type supported.

    Parameters
    ----------
    geometry : ``shapely.geometry``
    segmentize_value: float

    Returns
    -------
    geometry : ``shapely.geometry``
    """
    if geometry.geom_type != "Polygon":
        raise TypeError("segmentize geometry type must be Polygon")
    points = []
    p_xy = None
    for xy in geometry.exterior.coords:
        if p_xy is not None:
            line_segment = LineString([p_xy, xy])
            points.extend([
                line_segment.interpolate(segmentize_value * i).coords[0]
                for i in range(int(line_segment.length / segmentize_value))
            ])
        p_xy = xy
        points.append(xy)
    return Polygon(LinearRing(points))
Example #20
0
def v_type(p: Point2D, vertex: Point2D, n: Point2D) -> int:
    r = LinearRing([p, vertex, n])
    if not r.is_valid:
        return FLAT
    if r.is_ccw:
        return REGULAR
    return NON_REGULAR
Example #21
0
def build_circular_hatch(delta, offset, w, h):
    center_x = w / 2
    center_y = h / 2

    ls = []
    for r in np.arange(offset, math.sqrt(w * w + h * h), delta):
        # make a tiny circle as point in the center
        if r == 0:
            r = 0.001

        # compute a meaningful number of segment adapted to the circle's radius
        n = max(20, r)
        t = np.arange(0, 1, 1 / n)

        # A random phase is useful for circles that end up unmasked. If several such circles
        # start and stop at the same location, a disgraceful pattern will emerge when plotting.
        phase = random.random() * 2 * math.pi

        data = np.array([
            center_x + r * np.cos(t * math.pi * 2 + phase),
            center_y + r * np.sin(t * math.pi * 2 + phase),
        ]).T
        ls.append(LinearRing(data))

    mls = MultiLineString(ls)

    # Crop the circle to the final dimension
    p = Polygon([(0, 0), (w, 0), (w, h), (0, h)])
    return mls.intersection(p)
Example #22
0
def test_numpy_linearring_coords():
    from numpy.testing import assert_array_equal

    ring = LinearRing(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0)))
    ra = np.asarray(ring.coords)
    expected = np.asarray([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)])
    assert_array_equal(ra, expected)
Example #23
0
def simplify_ring(ring: LinearRing) -> LinearRing:
    ring = ring.simplify(0)
    cs = ring.coords
    if v_type(cs[-2], cs[0], cs[1]) == FLAT:
        cs = cs[1:-1]
        ring = LinearRing(ring)
    return ring
Example #24
0
def df_linear_ring():
    from shapely.geometry import LinearRing

    df = geopandas.GeoDataFrame(
        {"geometry": [LinearRing(((0, 0), (0, 1), (1, 1), (1, 0)))]},
        crs="epsg:4326")
    return df
Example #25
0
def test_linearring_from_too_short_linestring():
    # Creation of LinearRing request at least 3 coordinates (unclosed) or
    # 4 coordinates (closed)
    coords = [(0.0, 0.0), (1.0, 1.0)]
    line = LineString(coords)
    with pytest.raises(ValueError, match="requires at least 4 coordinates"):
        LinearRing(line)
Example #26
0
def test_linearring_from_unclosed_linestring():
    coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]
    line = LineString(coords[:-1])  # Pass in unclosed line
    ring = LinearRing(line)
    assert len(ring.coords) == 4
    assert ring.coords[:] == coords
    assert ring.geom_type == "LinearRing"
Example #27
0
    def sort_detection(self, temp_dir):
        origin_file = temp_dir
        output_file = "final_" + temp_dir

        if not os.path.isdir(output_file):
            os.mkdir(output_file)

        files = glob.glob(origin_file + '*.txt')
        files.sort()

        for i in files:
            out = i.replace(origin_file, output_file)
            fin = open(i, 'r').readlines()
            fout = open(out, 'w')
            for iline, line in enumerate(fin):
                ptr = line.strip().split(',####')
                rec = ptr[1]
                cors = ptr[0].split(',')
                assert (len(cors) % 2 == 0), 'cors invalid.'
                pts = [(int(cors[j]), int(cors[j + 1]))
                       for j in range(0, len(cors), 2)]
                try:
                    pgt = Polygon(pts)
                except Exception as e:
                    print(e)
                    print('An invalid detection in {} line {} is removed ... '.
                          format(i, iline))
                    continue

                if not pgt.is_valid:
                    print('An invalid detection in {} line {} is removed ... '.
                          format(i, iline))
                    continue

                pRing = LinearRing(pts)
                if pRing.is_ccw:
                    pts.reverse()
                outstr = ''
                for ipt in pts[:-1]:
                    outstr += (str(int(ipt[0])) + ',' + str(int(ipt[1])) + ',')
                outstr += (str(int(pts[-1][0])) + ',' + str(int(pts[-1][1])))
                outstr = outstr + ',####' + rec
                fout.writelines(outstr + '\n')
            fout.close()
        os.chdir(output_file)

        def zipdir(path, ziph):
            # ziph is zipfile handle
            for root, dirs, files in os.walk(path):
                for file in files:
                    ziph.write(os.path.join(root, file))

        zipf = zipfile.ZipFile('../det.zip', 'w', zipfile.ZIP_DEFLATED)
        zipdir('./', zipf)
        zipf.close()
        os.chdir("../")
        # clean temp files
        shutil.rmtree(origin_file)
        shutil.rmtree(output_file)
        return "det.zip"
Example #28
0
    def parse_query(self, query):
        super(MapPlotter, self).parse_query(query)

        self.projection = query.get('projection')

        self.area = query.get('area')

        names = []
        centroids = []
        all_rings = []
        data = None
        for idx, a in enumerate(self.area):
            if isinstance(a, basestring):
                a = a.encode("utf-8")
                sp = a.split('/', 1)
                if data is None:
                    data = list_areas(sp[0], simplify=False)

                b = [x for x in data if x.get('key') == a]
                a = b[0]
                self.area[idx] = a
            else:
                p = np.array(a['polygons'])
                p[:, :, 1] = pyresample.utils.wrap_longitudes(p[:, :, 1])
                a['polygons'] = p.tolist()
                del p

            rings = [LinearRing(po) for po in a['polygons']]
            if len(rings) > 1:
                u = cascaded_union(rings)
            else:
                u = rings[0]

            all_rings.append(u)
            if a.get('name'):
                names.append(a.get('name'))
                centroids.append(u.centroid)

        nc = sorted(zip(names, centroids))
        self.names = [n for (n, c) in nc]
        self.centroids = [c for (n, c) in nc]
        data = None

        if len(all_rings) > 1:
            combined = cascaded_union(all_rings)
        else:
            combined = all_rings[0]

        self.combined_area = combined
        combined = combined.envelope

        self.centroid = list(combined.centroid.coords)[0]
        self.bounds = combined.bounds

        self.show_bathymetry = bool(query.get('bathymetry'))
        self.show_area = bool(query.get('showarea'))

        self.quiver = query.get('quiver')

        self.contour = query.get('contour')
Example #29
0
    def gettheordertime(self):
        polys = sf.Reader("shapefiles/test/wholeArea.shp")
        polygon = polys.shapes()
        shpfilePoints = []
        for shape in polygon:
            shpfilePoints = shape.points
        polygon = Polygon(shpfilePoints)

        # #[锦里,九眼桥,锦江宾馆, 仁恒置地, 桐梓林, 骡马寺]
        # currentPoint = [30.662447, 104.072469] # 天府广场
        # points = [[30.650817,104.056385], [30.645582,104.095192], [30.654087,104.072528],
        #             [30.658646,104.072563], [30.621274,104.073749], [30.672531,104.071962]]
        # destination = [30.599595,104.040745] # 交界点

        point = Point(104.072469, 30.662447)  # 天府广场
        # point = Point(104.040745,30.599595) # keyPoint
        # point = Point(104.042779,30.620844)
        # point in polygon test
        if polygon.contains(point):
            print 'inside'
        else:
            print 'OUT'
            polExt = LinearRing(polygon.exterior.coords)
            d = polExt.project(point)
            p = polExt.interpolate(d)
            closest_point_coords = list(p.coords)[0]
            print list(p.coords)
            print d
def buffer_polygon(polygon, points):
    """
    Given a set of points outside a polygon, expand the polygon
    to include points within 250 meters
    Args:
        polygon - shapely polygon
        points - list of shapely points
    Returns:
        new polygon with buffered points added
    """
    not_close = []
    add_buffers = []

    poly_ext = LinearRing(polygon.exterior.coords)
    for point in points:
        # Find the distance between the point and the city polygon
        dist = polygon.distance(point)
        if dist > 250:
            not_close.append(point)
        else:
            # Create a line between the polygon and the point,
            # and buffer it
            point2 = poly_ext.interpolate(poly_ext.project(point))
            line = LineString([(point.x, point.y), (point2.x, point2.y)])
            buff = line.buffer(50)
            add_buffers.append(buff)
    for buff in add_buffers:
        polygon = polygon.union(buff)
    if not_close:
        print("{} crashes fell outside the buffered city polygon".format(
            len(not_close)))
    else:
        print("Expanded city polygon to include all crash locations")
    return polygon