def compute_intersection_demo():
    """
    calculating area of polygon inside region
    :return:
    """
    print("compute_intersection_demo")
    # http://toblerity.org/shapely/manual.html
    a = Point(1, 1).buffer(1.5)
    b = Point(2, 1).buffer(1.5)
    c = a.intersection(b)
    print("intersect area (circles): ", c.area)

    # http://toblerity.org/shapely/manual.html#polygons
    a = Polygon([(0, 0), (1, 1), (1, 0)])
    b = Polygon([(0.5, 0.5), (1.5, 1.5), (1.5, 0.5)])
    c = a.intersection(b)
    print("intersect area (polygons): ", c.area)
    # poly = Polygon(list(zip(X[0], Y[0])))

    # a = box(0, 0, 3, 3)  # patch
    b = Polygon([(0, 0), (0, 2), (2, 2), (2, 0)])  # roi
    c = Polygon([(0.5, 0.5), (1.0, 1.0), (1.5, 0.5), (1.0, 0.0)])  # polygon
    d = c.intersection(b)
    print("poly area", c.area)
    print("intersect area (poly, roi): ", d.area)
    # WITHIN:
    # object's boundary and interior intersect only with the interior of the other
    # (not its boundary or exterior)
    print("poly within roi: ", c.within(b))
    # CROSSES:
    # interior of the object intersects the interior of the other but does not contain it...
    print("poly crosses roi: ", c.crosses(b))
    # DISJOINT: boundary and interior of the object do not intersect at all
    print("poly does not intersect roi: ", c.disjoint(b))
Beispiel #2
0
class Poly:

    def __init__(self, coords, height):
        self._polygon = Polygon(coords)
        self._height = height

    @property
    def height(self):
        return self._height

    @property
    def coords(self):
        return list(self._polygon.exterior.coords)[:-1]
    
    @property
    def area(self):
        return self._polygon.area

    @property
    def center(self):
        return (self._polygon.centroid.x, self._polygon.centroid.y)

    def contains(self, point):
        point = Point(point)
        return self._polygon.contains(point)

    def crosses(self, other):
        return self._polygon.crosses(other)
Beispiel #3
0
class Prism():
    """
    3D structure Prism = 2D Polygon + height
    """
    
    def __init__(self, corners, height):
        self.p = Polygon(corners)
        self.height = height
        
        self.poly = (self.p, self.height)
        
    def __str__(self):
        return '(' + str(self.p) + ',' + str(self.height) + ')'
    
    def crosses(self, line):
        """
        shapely geometry objects have a method .crosses which return 
        True if the geometries cross paths.
        Input: line (from shapely.geometry import LineString)
                or list(tuple1, tuple2, tuple3...)
                or (tuple1, tuple2,...)
        if points = [tuple1, tuple]
        """
        #print('crosses', line, type(line))
        if not type(line) == LineString:
            #print(line, type(line))
            line = LineString(list(line))
        #coords = list(zip(*line)) #[(x1,x2),(y1,y2),(z1,z2)]
        return self.p.crosses(line)
    
    def intersects(self,line):
        #print('crosses', line, type(line))
        if not type(line) == LineString:
            #print(line, type(line))
            line = LineString(list(line))
        #coords = list(zip(*line)) #[(x1,x2),(y1,y2),(z1,z2)]
        return self.p.intersects(line)
        
    def touches(self,line):
        #print('crosses', line, type(line))
        if not type(line) == LineString:
            #print(line, type(line))
            line = LineString(list(line))
        #coords = list(zip(*line)) #[(x1,x2),(y1,y2),(z1,z2)]
        return self.p.touches(line)
    
    def bounds(self):
        """
        Returns a (minx, miny, maxx, maxy) tuple (float values) that bounds the object
        """
        return self.p.bounds
    
    def intersection(self, line):
        """
        Returns a representation of the intersection of this object with the other geometric object.
        """
        if not type(line) == LineString:
            line = LineString(list(line))
        return self.p.intersection(line)
Beispiel #4
0
def plateau_to_building(data):

    if "building_limits" not in data:
        raise ValueError("Building limits does not exist.")
    if "height_plateaus" not in data:
        raise ValueError("Height plateaus does not exist.")

    building_coors = data["building_limits"]["features"][0]["geometry"][
        "coordinates"][0]
    building_obj = Polygon(building_coors)

    if "building_and_height" in data:
        return "Building limits with heights already exist"
    else:
        data["building_and_height"] = {
            "type": "FeatureCollection",
            "features": []
        }

    total_area = 0.0
    plateau_intersec = Polygon(
        data["height_plateaus"]["features"][0]["geometry"]["coordinates"][0])
    for i in range(len(data["height_plateaus"]["features"])):
        plateau_coors = data["height_plateaus"]["features"][i]["geometry"][
            "coordinates"][0]
        elevation = data["height_plateaus"]["features"][i]["properties"][
            "elevation"]
        plateau_obj = Polygon(plateau_coors)
        if i > 0:
            if plateau_intersec.crosses(plateau_obj):
                raise ValueError(
                    "There is an overlapping between height plateaus coordinates"
                )
            if plateau_intersec.disjoint(plateau_obj):
                raise ValueError(
                    "There is a gap between height plateaus coordinates")
        total_area += plateau_obj.area
        plateau_intersec = plateau_intersec.union(plateau_obj)

        building_plateau = list(
            building_obj.intersection(plateau_obj).exterior.coords)
        data["building_and_height"]["features"].append({
            "geometry": {
                "coordinates": [building_plateau],
                "type": "Polygon"
            },
            "properties": {
                "elevation": elevation
            },
            "type": "Feature"
        })
    if not plateau_intersec.contains(building_obj):
        raise ValueError("Height plateaus does not cover building limits")

    with portalocker.Lock(OUTPUT_JSON_PATH, 'w+') as f:
        json.dump(data, f, indent=4)
        return "Success. Json file saved in {}".format(OUTPUT_PATH)
Beispiel #5
0
 def _calculate_position_between_objects(self, boxA: BoundBox,
                                         boxB: BoundBox):
     polygon = Polygon(self.convert_top_bottom_to_polygon(boxA))
     other_polygon = Polygon(self.convert_top_bottom_to_polygon(boxB))
     vsName = boxA.label + ' vs ' + boxB.label
     positions = {vsName: {}}
     # positions[vsName]
     if polygon.crosses(other_polygon):
         positions[vsName]['crosses'] = polygon.crosses(other_polygon)
     if polygon.contains(other_polygon):
         positions[vsName]['contains'] = polygon.contains(other_polygon)
     if polygon.disjoint(other_polygon):
         positions[vsName]['disjoint'] = polygon.disjoint(other_polygon)
     if polygon.intersects(other_polygon):
         positions[vsName]['intersects'] = polygon.intersects(other_polygon)
     if polygon.overlaps(other_polygon):
         positions[vsName]['overlaps'] = polygon.overlaps(other_polygon)
     if polygon.touches(other_polygon):
         positions[vsName]['touches'] = polygon.touches(other_polygon)
     if polygon.within(other_polygon):
         positions[vsName]['within'] = polygon.within(other_polygon)
     return positions
Beispiel #6
0
class Prism():
    """
    3D structure Prism = 2D Polygon + height
    """
    def __init__(self, corners, height):
        self.p = Polygon(corners)
        self.height = height

        self.poly = (self.p, self.height)

    def __str__(self):
        return '(' + str(self.p) + ',' + str(self.height) + ')'

    def crosses(self, *line):
        """shapely geometry objects have a method .crosses which return 
        True if the geometries cross paths.
        Input: line (from shapely.geometry import LineString)
                or list(tuple1, tuple2, tuple3...)
                or (tuple1, tuple2,...)
        if points = [tuple1, tuple]
        """
        if not type(line) == LineString:
            line = LineString(list(line))
        #coords = list(zip(*line)) #[(x1,x2),(y1,y2),(z1,z2)]
        return self.p.crosses(line)

    def bounds(self):
        """
        Returns a (minx, miny, maxx, maxy) tuple (float values) that bounds the object
        """
        return self.p.bounds

    def intersection(self, *line):
        """
        Returns a representation of the intersection of this object with the other geometric object.
        """
        if not type(line) == LineString:
            line = LineString(list(line))
        return self.p.intersection(line)

    def localgoal(self, path, ind):
        loc_goal = []
        while not loc_goal and ind < len(path):
            if self.crosses(path[ind], path[ind + 1]):
                loc_goal = self.p.intersection(path[ind], path[ind + 1])
                break
            else:
                ind += 1
            if loc_goal == []:
                print("Failed to find a new local goal!")
        return loc_goal, ind
Beispiel #7
0
def test_prepared_predicates():
    # check prepared predicates give the same result as regular predicates
    polygon1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)])
    polygon2 = Polygon([(0.5, 0.5), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5)])
    point2 = Point(0.5, 0.5)
    polygon_empty = Polygon()
    prepared_polygon1 = PreparedGeometry(polygon1)
    for geom2 in (polygon2, point2, polygon_empty):
        assert polygon1.disjoint(geom2) == prepared_polygon1.disjoint(geom2)
        assert polygon1.touches(geom2) == prepared_polygon1.touches(geom2)
        assert polygon1.intersects(geom2) == prepared_polygon1.intersects(
            geom2)
        assert polygon1.crosses(geom2) == prepared_polygon1.crosses(geom2)
        assert polygon1.within(geom2) == prepared_polygon1.within(geom2)
        assert polygon1.contains(geom2) == prepared_polygon1.contains(geom2)
        assert polygon1.overlaps(geom2) == prepared_polygon1.overlaps(geom2)
    def update(self, agent_coor, goal):
        ind = random.randint(0, len(self.polygon_list) - 1)
        old_polygon = self.polygon_list[ind]

        count = 5
        move_success = False
        while count > 0 and not move_success:
            print("Count", count)
            pol_move = random.choice(self.list_move)
            new_polygon = []
            for point in old_polygon:
                point = np.array(point) + pol_move
                new_polygon.append(tuple(point))
            print(new_polygon, old_polygon)

            new_polygon_obj = Polygon(new_polygon)
            agent_point = Point(agent_coor[1], agent_coor[0])

            flag = True

            if new_polygon_obj.touches(
                    agent_point) or new_polygon_obj.overlaps(
                        agent_point) or new_polygon_obj.crosses(agent_point):
                count -= 1
                flag = False
            else:
                for i, p in enumerate(self.polygon_objs):
                    if i != ind and (new_polygon_obj.overlaps(p)
                                     or new_polygon_obj.touches(p) or
                                     new_polygon_obj.intersects(agent_point)):
                        count -= 1
                        flag = False
                        break

            if flag:
                move_success = True

        if not move_success:
            return

        self.__draw.polygon(old_polygon, outline=0)

        print(f"Polygon {ind} move {pol_move}")
        self.__draw.polygon(new_polygon, outline=ind + 1)
        self.polygon_list[ind] = new_polygon
        self.polygon_objs[ind] = new_polygon_obj
Beispiel #9
0
def test_prepared_predicates():
    # check prepared predicates give the same result as regular predicates
    polygon1 = Polygon([
        (0, 0), (0, 1), (1, 1), (1, 0), (0, 0)
    ])
    polygon2 = Polygon([
        (0.5, 0.5), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5)
    ])
    point2 = Point(0.5, 0.5)
    polygon_empty = Polygon()
    prepared_polygon1 = PreparedGeometry(polygon1)
    for geom2 in (polygon2, point2, polygon_empty):
        assert polygon1.disjoint(geom2) == prepared_polygon1.disjoint(geom2)
        assert polygon1.touches(geom2) == prepared_polygon1.touches(geom2)
        assert polygon1.intersects(geom2) == prepared_polygon1.intersects(geom2)
        assert polygon1.crosses(geom2) == prepared_polygon1.crosses(geom2)
        assert polygon1.within(geom2) == prepared_polygon1.within(geom2)
        assert polygon1.contains(geom2) == prepared_polygon1.contains(geom2)
        assert polygon1.overlaps(geom2) == prepared_polygon1.overlaps(geom2)
Beispiel #10
0
class Obstacle:
    def __init__(self, corners, height):
        self._polygon = Polygon(corners)
        self._height = height

    @property
    def centroid(self):
        return self._polygon.centroid.x, self._polygon.centroid.y

    @property
    def height(self):
        return self._height

    def contains(self, point):
        return point[2] <= self._height and self._polygon.contains(
            Point(point[0:2]))

    def crosses(self, line):
        return self._polygon.crosses(line)