示例#1
0
def get_lawn_region_plot(lawn_points, region_points):
    """
    plot the lawn area on top of the entire region

    parameters:
    - lawn_points : list of lists of tuples
        list of list of two tuples, consisting of the endpoints 
        of segments corresponding to lawn
    - region_points : list of lists of tuples
        list of list of two tuples, consisting of the endpoints 
        of segments corresponding to whole region

    returns:
    - fig: matplotlib.figure object
    - ax: matplotlib.axes object
    """

    fig, ax = mplt.subplots(figsize=(12,8))

    pp = mcl.LineCollection(region_points, linewidths=1, colors='r')
    lp = mcl.LineCollection(lawn_points, linewidths=2, colors='k')

    ax.add_collection(pp)
    ax.add_collection(lp)

    lawn_perimeter = np.array(lawn_points).reshape(-1,2)[::2]
    lawn_perimeter = np.vstack((lawn_perimeter, lawn_perimeter[0]))

    path = mpath.Path(lawn_perimeter, closed=True)
    patch = mpatch.PathPatch(path, facecolor='green', alpha=0.3)
    ax.add_patch(patch);

    region_perimeter = np.array(region_points).reshape(-1,2)[::2]
    region_perimeter = np.vstack((region_perimeter, region_perimeter[0]))

    lawn_polygon = Polygon(lawn_perimeter)
    region_polygon = Polygon(region_perimeter)
    excluded_polygon = region_polygon.difference(lawn_polygon)
    excluded_perimeter = np.array(excluded_polygon.exterior.coords)

    path = mpath.Path(excluded_perimeter, closed=True)
    patch = mpatch.PathPatch(path, facecolor='black', alpha=0.3)
    ax.add_patch(patch);

    ax.set_xlabel('n', fontsize=14);
    ax.set_ylabel('n', fontsize=14);
    ax.set_xlim(-1, 16);
    ax.set_ylim(-1, 11);
    ax.autoscale();
    ax.margins(0.1);
    ax.axis('off');

    return fig, ax
def shape_substract(x_envelope_1, x_envelope_2, y_envelope_1, y_envelope_2):
    a = Shape()
    poly_1 = Shape()
    poly_2 = Shape()
    poly_1 = Shape([(x_envelope_1[j], y_envelope_1[j])
                    for j in range(len(x_envelope_1))])
    poly_2 = Shape([(x_envelope_2[j], y_envelope_2[j])
                    for j in range(len(x_envelope_2))])
    a = poly_2.difference(poly_1)
    tx = []
    ty = []
    t_x, t_y = a.exterior.xy
    return t_x, t_y
示例#3
0
def rectangle_with_mounting_holes(width, height, inset, hole_shift, hole_drill):
    shift_matrix = np.array([[1, 1], [-1, 1], [-1, -1], [1, -1]])

    exterior_coords = np.array(
        [[0, 0], [width, 0], [width, height], [0, height]])
    interior_coords = exterior_coords + shift_matrix * inset
    interior = Polygon(interior_coords)

    hole_coords = exterior_coords + shift_matrix * hole_shift
    holes = []
    for pos in hole_coords:
        holes.append(Hole(pos, hole_drill))
        hole_clearance = hole_drill / 2 + inset
        interior = interior.difference(
            Polygon(shift_matrix * hole_clearance + pos))

    outline = Polygon(exterior_coords, [interior.exterior.coords])
    return Outline(outline, *holes)
示例#4
0
def kml_to_shapely(data: str) -> Borders:
    """

    :rtype: Borders
    :param data:
    """

    tree = fromstring(data)
    rv = []
    for placemark in tree.findall(".//" + ns + "Placemark"):
        name = placemark.findtext(ns + "name")
        __log.debug("Parsing placemark: %s", name)
        # MultiGeometry lub LinearRing?
        geo = placemark.find(ns + "MultiGeometry")
        description = BeautifulSoup(
            placemark.findtext("{http://www.opengis.net/kml/2.2}description"),
            "html.parser",
        )
        tags = dict(
            zip(
                map(lambda x: x.text,
                    description.find_all("span", class_="atr-name")),
                map(lambda x: x.text,
                    description.find_all("span", class_="atr-value")),
            ))
        outer = Polygon()
        inner = Polygon()
        for polygon in geo.findall(ns + "Polygon"):
            outer = cascaded_union([
                ring_to_shape(x)
                for x in polygon.findall(ns + "outerBoundaryIs/" + ns +
                                         "LinearRing")
            ] + [outer])
            inner = cascaded_union([
                ring_to_shape(x)
                for x in polygon.findall(ns + "innerBoundaryIs/" + ns +
                                         "LinearRing")
            ] + [inner])
        border = Feature(outer.difference(inner))
        border.set_tag("name", name)
        for key, value in tags.items():
            border.set_tag(key, value)
        rv.append(border)
    return rv
示例#5
0
def operation_example():
	patch = Point(0.0, 0.0).buffer(10.0)
	print('patch = {}.'.format(patch))
	print('patch.area = {}.'.format(patch.area))

	line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
	dilated = line.buffer(0.5)
	eroded = dilated.buffer(-0.3)

	ring = LinearRing([(0, 0), (1, 1), (1, 0)])

	point = Point(0.5, 0.5)
	polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
	print('polygon.contains(point) = {}.'.format(polygon.contains(point)))

	#box = shapely.geometry.box(minx, miny, maxx, maxy, ccw=True)

	pa = asPoint(np.array([0.0, 0.0]))
	la = asLineString(np.array([[1.0, 2.0], [3.0, 4.0]]))
	ma = asMultiPoint(np.array([[1.1, 2.2], [3.3, 4.4], [5.5, 6.6]]))

	data = {'type': 'Point', 'coordinates': (0.0, 0.0)}
	geom = shapely.geometry.shape(data)
	#geom = shapely.geometry.asShape(data)

	#--------------------
	#geom = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
	geom = LineString([(0, 0), (10, 0), (10, 5), (20, 5)])

	print('polygon.has_z = {}.'.format(geom.has_z))
	if isinstance(geom, LinearRing):
		print('polygon.is_ccw = {}.'.format(geom.is_ccw))  # LinearRing only.
	print('polygon.is_empty = {}.'.format(geom.is_empty))
	print('polygon.is_ring = {}.'.format(geom.is_ring))
	print('polygon.is_simple = {}.'.format(geom.is_simple))
	print('polygon.is_valid = {}.'.format(geom.is_valid))

	print('polygon.coords = {}.'.format(geom.coords))

	print('polygon.area = {}.'.format(geom.area))
	print('polygon.bounds = {}.'.format(geom.bounds))
	print('polygon.length = {}.'.format(geom.length))
	print('polygon.minimum_clearance = {}.'.format(geom.minimum_clearance))
	print('polygon.geom_type = {}.'.format(geom.geom_type))

	print('polygon.boundary = {}.'.format(geom.boundary))
	print('polygon.centroid = {}.'.format(geom.centroid))

	print('polygon.convex_hull.exterior.coords.xy = {}.'.format(list((x, y) for x, y in zip(*geom.convex_hull.exterior.coords.xy))))
	print('polygon.envelope = {}.'.format(geom.envelope))
	print('polygon.minimum_rotated_rectangle = {}.'.format(geom.minimum_rotated_rectangle))

	#polygon.parallel_offset(distance, side, resolution=16, join_style=1, mitre_limit=5.0)
	#polygon.simplify(tolerance, preserve_topology=True)

	#--------------------
	poly1 = Polygon([(3, 3), (5, 3), (5, 5), (3, 5)])
	poly2 = Polygon([(1, 1), (4, 1), (4, 3.5), (1, 3.5)])

	print('poly1.intersection(poly2) = {}.'.format(poly1.intersection(poly2)))
	print('poly1.difference(poly2) = {}.'.format(poly1.difference(poly2)))
	print('poly1.symmetric_difference(poly2) = {}.'.format(poly1.symmetric_difference(poly2)))
	print('poly1.union(poly2) = {}.'.format(poly1.union(poly2)))

	print('poly1.equals(poly2) = {}.'.format(poly1.equals(poly2)))
	print('poly1.almost_equals(poly2, decimal=6) = {}.'.format(poly1.almost_equals(poly2, decimal=6)))
	print('poly1.contains(poly2) = {}.'.format(poly1.contains(poly2)))
	print('poly1.covers(poly2) = {}.'.format(poly1.covers(poly2)))
	print('poly1.crosses(poly2) = {}.'.format(poly1.crosses(poly2)))
	print('poly1.disjoint(poly2) = {}.'.format(poly1.disjoint(poly2)))
	print('poly1.intersects(poly2) = {}.'.format(poly1.intersects(poly2)))
	print('poly1.overlaps(poly2) = {}.'.format(poly1.overlaps(poly2)))
	print('poly1.touches(poly2) = {}.'.format(poly1.touches(poly2)))
	print('poly1.within(poly2) = {}.'.format(poly1.within(poly2)))

	#--------------------
	poly1 = Polygon([(40, 50), (60, 50), (60, 90), (40, 90)])
	poly2 = Polygon([(10, 100), (100, 100), (100, 150), (10, 150)])

	print('The distance between two convex polygons = {}.'.format(poly1.distance(poly2)))
	print('The Hausdorff distance between two convex polygons = {}.'.format(poly1.hausdorff_distance(poly2)))
	print('The representative point of a polygon = {}.'.format(poly1.representative_point()))

	#--------------------
	lines = [
		((0, 0), (1, 1)),
		((0, 0), (0, 1)),
		((0, 1), (1, 1)),
		((1, 1), (1, 0)),
		((1, 0), (0, 0)),
		((1, 1), (2, 0)),
		((2, 0), (1, 0)),
		((5, 5), (6, 6)),
		((1, 1), (100, 100)),
	]

	polys = shapely.ops.polygonize(lines)
	result, dangles, cuts, invalids = shapely.ops.polygonize_full(lines)
	merged_line = shapely.ops.linemerge(lines)

	# Efficient unions.
	polygons = [Point(i, 0).buffer(0.7) for i in range(5)]
	shapely.ops.unary_union(polygons)
	shapely.ops.cascaded_union(polygons)

	# Delaunay triangulation.
	points = MultiPoint([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
	triangles = shapely.ops.triangulate(points)

	# Voronoi diagram.
	#points = MultiPoint([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
	#regions = shapely.ops.voronoi_diagram(points)

	# Nearest points.
	triangle = Polygon([(0, 0), (1, 0), (0.5, 1), (0, 0)])
	square = Polygon([(0, 2), (1, 2), (1, 3), (0, 3), (0, 2)])
	nearest_points = shapely.ops.nearest_points(triangle, square)

	square = Polygon([(1,1), (2, 1), (2, 2), (1, 2), (1, 1)])
	line = LineString([(0,0), (0.8, 0.8), (1.8, 0.95), (2.6, 0.5)])
	result = shapely.ops.snap(line, square, 0.5)

	g1 = LineString([(0, 0), (10, 0), (10, 5), (20, 5)])
	g2 = LineString([(5, 0), (30, 0), (30, 5), (0, 5)])
	forward, backward = shapely.ops.shared_paths(g1, g2)

	pt = Point((1, 1))
	line = LineString([(0, 0), (2, 2)])
	result = shapely.ops.split(line, pt)

	ls = LineString((i, 0) for i in range(6))
	shapely.ops.substring(ls, start_dist=1, end_dist=3)
	shapely.ops.substring(ls, start_dist=3, end_dist=1)
	shapely.ops.substring(ls, start_dist=1, end_dist=-3)
	shapely.ops.substring(ls, start_dist=0.2, end_dist=-0.6, normalized=True)
示例#6
0
def lapMetrics(poses: np.ndarray,
               timestamps: np.ndarray,
               innerboundary_poly: Polygon,
               outerboundary_poly: Polygon,
               car_geom: deepracing.CarGeometry = deepracing.CarGeometry()):
    wheel_positions_global = np.matmul(
        poses, car_geom.wheelPositions(dtype=poses.dtype))[:, 0:3]
    delta_poly: Polygon = outerboundary_poly.difference(innerboundary_poly)
    violations = np.zeros_like(wheel_positions_global[:, 0, 0], dtype=bool)
    wheels_on_track = np.zeros((wheel_positions_global.shape[0], 4),
                               dtype=bool)
    wheel_distances = np.zeros((wheel_positions_global.shape[0], 4),
                               dtype=np.float64)
    distances = np.zeros_like(wheel_positions_global[:, 0, 0],
                              dtype=np.float64)
    for i in tqdm(range(wheel_positions_global.shape[0]),
                  desc="Checking for boundary violations",
                  total=wheel_positions_global.shape[0]):
        wheel_positions = wheel_positions_global[i]
        wheel_distances[i] = np.asarray([
            delta_poly.distance(
                ShapelyPoint(wheel_positions[0, j], wheel_positions[2, j]))
            for j in range(4)
        ],
                                        dtype=np.float64)
        wheels_on_track[i] = np.asarray([
            delta_poly.contains(
                ShapelyPoint(wheel_positions[0, j], wheel_positions[2, j]))
            for j in range(4)
        ],
                                        dtype=bool)
        violations[i] = wheels_on_track[i].sum() < 2
        if violations[i]:
            distances[i] = np.min(wheel_distances[i, ~wheels_on_track[i]])

    # inside_violations = np.array([innerboundary_poly.contains(ShapelyPoint(positions[i,0], positions[i,2])) for i in range(positions.shape[0])])
    # outside_violations = np.array([not outerboundary_poly.contains(ShapelyPoint(positions[i,0], positions[i,2])) for i in range(positions.shape[0])])

    # inner_contiguous_regions = contiguous_regions(inside_violations)
    # outer_contiguous_regions = contiguous_regions(outside_violations)
    # outside_violation_regions = np.column_stack([outer_contiguous_regions, 1*np.ones([outer_contiguous_regions.shape[0], 1], dtype=np.int64)])
    # inside_violation_regions = np.column_stack([inner_contiguous_regions, -1*np.ones([inner_contiguous_regions.shape[0], 1], dtype=np.int64)])

    all_violation_regions = contiguous_regions(violations)

    # I = np.argsort(all_violation_regions[:,0])
    # all_violation_regions = all_violation_regions[I]

    t0 = timestamps[0]
    tbf = []
    bfmaxdists = []
    bfmeandists = []
    bftimes = []
    positions = poses[:, 0:3, 3]
    for i in range(all_violation_regions.shape[0]):
        region = all_violation_regions[i]
        tf = timestamps[region[0]]
        dt = tf - t0
        tbf.append(dt)
        t0 = timestamps[region[1]]
        idx = np.arange(region[0], region[1] + 1, step=1, dtype=np.int64)
        points = positions[idx]
        timestampslocal = timestamps[idx]
        bftimes.append(timestampslocal[-1] - timestampslocal[0])
        # if region[2]<0:
        #     distances = np.array([innerboundary_poly.exterior.distance(ShapelyPoint(points[j,0], points[j,2])) for j in range(points.shape[0])])
        # else:
        #     distances = np.array([outerboundary_poly.distance(ShapelyPoint(points[j,0], points[j,2])) for j in range(points.shape[0])])
        # distances = np.array([delta_poly.distance(ShapelyPoint(points[j,0], points[j,2])) for j in range(points.shape[0])])
        bfmeandists.append(float(np.mean(distances[idx])))
        bfmaxdists.append(float(np.max(distances[idx])))
    if violations.shape[0] > 0:
        ratio_on_track = 1.0 - np.sum(violations) / float(violations.shape[0])
    else:
        ratio_on_track = 1.0
    return all_violation_regions, {
        "ratio_on_track": ratio_on_track,
        "number_boundary_failures": all_violation_regions.shape[0],
        "time_between_failures": tbf,
        "boundary_failure_max_distances": bfmaxdists,
        "boundary_failure_mean_distances": bfmeandists,
        "boundary_failure_times": bftimes
    }
示例#7
0
def shape_split(vert, l_split, b_split, l, b):
    ###############
    ### Here getting the coordinates of the split axis drwan
    x_drawn = [vert[k][0] for k in range(len(vert))]
    y_drawn = [vert[k][1] for k in range(len(vert))]
    x_st = x_drawn[0]  #x_st[n_bod-1]=x
    y_st = y_drawn[0]  #y_st[n_bod-1]=y
    x_end = x_drawn[-1]
    y_end = y_drawn[-1]

    ###############
    ### figuring out where does the drwan axis fall in the body to be split
    print("start index for split")
    temp_d = []
    temp_d = [
        math.sqrt((l_split[i] - x_st)**2 + (b_split[i] - y_st)**2)
        for i in range(len(l_split))
    ]
    split_st_index = temp_d.index(min(temp_d))
    print("end index for print ")
    temp_d = []
    temp_d = [
        math.sqrt((l_split[i] - x_end)**2 + (b_split[i] - y_end)**2)
        for i in range(len(l_split))
    ]
    split_end_index = temp_d.index(min(temp_d))
    print('updating path ')

    # calculating the x and y of the node to be inserted
    # x = (x-1) +( x+1)
    #
    l_insert_st = (l_split[split_st_index] + l_split[split_st_index + 1]) / 2
    b_insert_st = (b_split[split_st_index] + b_split[split_st_index + 1]) / 2
    l_insert_end = (l_split[split_end_index] +
                    l_split[split_end_index - 1]) / 2
    b_insert_end = (b_split[split_end_index] +
                    b_split[split_end_index - 1]) / 2
    '''
    #####
    # Now need to put this in the original enevelop
    l_split.insert(split_st_index,l_insert_st)
    b_split.insert(split_st_index,b_insert_st)
    l_split.insert(split_end_index,l_insert_end)
    b_split.insert(split_end_index,b_insert_end)
    '''

    path = []
    vert = []
    print("adding in the start from the actual body")
    for k in range(0, split_st_index + 1):
        print(k)
        vert.append((l_split[k], b_split[k]))
    print("adding the drwan points")
    for f in range(len(x_drawn)):
        vert.append((x_drawn[f], y_drawn[f]))
    #    path, = ax.plot([x_drawn[f]],[y_drawn[f]],'o-',lw=1,color=color)
    # just append the end part of the split axis buy but have append what ever is drwan
    # append the end point of the axis
    print("adding in the end from the actual body")
    for k in range(split_end_index, len(l_split)):
        print(k)
        vert.append((l_split[k], b_split[k]))

    #    path, = ax.plot([l_split[k]],[b_split[k]],'o-',lw=1,color=color)
    # close the body
    ## calculating inserted body
    temp_1_shape = Shape(vert[:][:])
    temp_2_shape = Shape([(l_split[k], b_split[k]) for k in range(len(l))])
    a = Shape()
    xa = []
    ya = []
    a = temp_2_shape.difference(
        temp_1_shape)  # this the left over part of the splitted body
    err = a.is_valid
    print(a.exterior.coords)
    xa, ya = a.exterior.xy
    return xa, ya, a, err
示例#8
0
 def make_buffer(self, thickness):
     inner = self.polygon
     outer = Polygon(inner.buffer(thickness).exterior)
     return outer.difference(inner)