def covered_area(tour, mapping, r):
	"""
	Function will print info about the path
	"""

	if isinstance(mapping[tour[0]][0], classes.PointSegment):
		coord = mapping[tour[0]][0].coord
		seg = Point(coord)
	elif isinstance(mapping[tour[0]][0], classes.LineSegment):
		coords = mapping[tour[0]][0].coords
		seg = LineString(coords)

	segment_area = seg.buffer(r)
	
	polygons = []
	# Now compute the cost of the transitions
	for i in range(1, len(tour)):
		segment = mapping[tour[i]][0]

		if isinstance(segment, classes.PointSegment):
			coord = segment.coord
			seg = Point(coord)
		elif isinstance(segment, classes.LineSegment):
			coords = segment.coords
			seg = LineString(coords)

		#polygons.append(seg.buffer(r))
		segment_area = segment_area.union(seg.buffer(r+0.00001))

	#total_area = cascaded_union(polygons)

	#return total_area.area
	return segment_area.area
Exemple #2
0
    def _populate_shapes(self):
        """ Set values for self._label_shapes, _footprint_shape, and others.
        """
        point = Point(self.position.x, self.position.y)
        point_buffered = point.buffer(self.radius + self.buffer, 3)
        self._point_shape = point.buffer(self.radius, 3)
        
        scale = 10.0
        font = truetype(self.fontfile, int(self.fontsize * scale), encoding='unic')

        x, y = self.position.x, self.position.y
        w, h = font.getsize(self.name)
        w, h = w/scale, h/scale
        
        for placement in placements:
            label_shape = point_label_bounds(x, y, w, h, self.radius, placement)
            mask_shape = label_shape.buffer(self.buffer, 2).union(point_buffered)
            
            self._label_shapes[placement] = label_shape
            self._mask_shapes[placement] = mask_shape
    
        unionize = lambda a, b: a.union(b)
        self._label_footprint = reduce(unionize, self._label_shapes.values())
        self._mask_footprint = reduce(unionize, self._mask_shapes.values())
        
        # number of pixels from the top of the label based on the bottom of a "."
        self._baseline = font.getmask('.').getbbox()[3] / scale
Exemple #3
0
    def test_operations(self):
        point = Point(0.0, 0.0)

        # General geometry
        self.assertEqual(point.area, 0.0)
        self.assertEqual(point.length, 0.0)
        self.assertAlmostEqual(point.distance(Point(-1.0, -1.0)),
                               1.4142135623730951)

        # Topology operations

        # Envelope
        self.assertIsInstance(point.envelope, Point)

        # Intersection
        self.assertIsInstance(point.intersection(Point(-1, -1)),
                              GeometryCollection)

        # Buffer
        self.assertIsInstance(point.buffer(10.0), Polygon)
        self.assertIsInstance(point.buffer(10.0, 32), Polygon)

        # Simplify
        p = loads('POLYGON ((120 120, 121 121, 122 122, 220 120, 180 199, '
                  '160 200, 140 199, 120 120))')
        expected = loads('POLYGON ((120 120, 140 199, 160 200, 180 199, '
                         '220 120, 120 120))')
        s = p.simplify(10.0, preserve_topology=False)
        self.assertTrue(s.equals_exact(expected, 0.001))

        p = loads('POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200),'
                  '(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))')
        expected = loads(
            'POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200),'
            '(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))')
        s = p.simplify(10.0, preserve_topology=True)
        self.assertTrue(s.equals_exact(expected, 0.001))

        # Convex Hull
        self.assertIsInstance(point.convex_hull, Point)

        # Differences
        self.assertIsInstance(point.difference(Point(-1, 1)), Point)

        self.assertIsInstance(point.symmetric_difference(Point(-1, 1)),
                              MultiPoint)

        # Boundary
        self.assertIsInstance(point.boundary, GeometryCollection)

        # Union
        self.assertIsInstance(point.union(Point(-1, 1)), MultiPoint)

        self.assertIsInstance(point.representative_point(), Point)

        self.assertIsInstance(point.centroid, Point)

        # Relate
        self.assertEqual(point.relate(Point(-1, -1)), 'FF0FFF0F2')
Exemple #4
0
    def is_at_goal(self):
        """Check if the robot is near its goal in both distance and rotation.

        Once the robot is near its goal, it rotates towards the final goal
        pose. Once it reaches this goal pose (within some predetermined
        rotation allowance), it is deemed to be at its goal.

        Returns
        -------
        bool
            True if the robot is at its goal, false otherwise.
        """

        goal_pt = Point(self.goal_pose[0:2])
        approximation_circle = goal_pt.buffer(self.distance_allowance)
        pose_pt = Point(self.robot.pose2D.pose[0:2])
        position_bool = approximation_circle.contains(pose_pt)
        logging.debug('Position is {}'.format(position_bool))

        degrees_to_goal = abs(self.robot.pose2D.pose[2] - self.goal_pose[2])
        orientation_bool = (degrees_to_goal < self.rotation_allowance)
        # <>TODO: Replace with ros goal message check
        if self.robot.publish_to_ROS is True:
            orientation_bool = True
        logging.debug('Orientation is {}'.format(orientation_bool))

        logging.debug('is_at_goal = {}'.format((position_bool and
                                                orientation_bool)))
        return position_bool and orientation_bool
    def evaluate(self, action, zones, graph):

        scenario = Scenario_Generator(
            self.width,
            self.height,
            self.immobile_objs,
            self.mobile_objs,
            self.manipulatable_obj,
            self.target_obj,
            showRender=False,
        )
        game_objects = scenario.getGameObjects()
        end_position, shape = scenario.evaluate(action)
        radius = shape.radius
        end_position = Point(end_position)
        circular_region_ball = end_position.buffer(radius)
        occupied_zones = []
        for i in xrange(len(zones)):
            if zones[i].intersects(circular_region_ball):
                occupied_zones.append(i)
        if len(occupied_zones) == 0:
            return len(zones)  # set to the maximum length
        min_d = 9999
        for occupied_zone in occupied_zones:
            length = nx.shortest_path_length(graph, source=occupied_zone, target=self.target_zone)

            if length < min_d:
                min_d = length

        return min_d
Exemple #6
0
def batch(num_features):
    # Coordinate values in range [0, 50]
    x = partial(random.uniform, 0.0, 50.0)
    # radii in range [0.01, 0.5]
    r = partial(random.uniform, 0.01, 0.5)
    # Poisson-distributed resolution k
    def k(expectation=1):
        #partial(random.randint, 1, 4)
        L = math.exp(-expectation)
        k = 0
        p = 1
        while p > L:
            k = k + 1
            u = random.uniform(0.0, 1.0)
            p = p * u
        return k - 1


    batch = {'index': []}
    for i in xrange(num_features):
        point = Point(x(), x())
        polygon = point.buffer(r(), k())
        batch['index'].append(dict(
            id=str(i+1), 
            bbox=polygon.bounds, 
            geometry=mapping(polygon), 
            properties=dict(title='Feature %d' % (i+1)))
            )
    return batch
Exemple #7
0
 def case_present_past_future(self, stage):
     results = {}
     for e in self.elements:
         data = stage.element_data(e)
         p = Point(data['center_x'], 500 - data['center_y'])
         results[e] = {
             'point': p.buffer(data['radius'])
         }
     return results
Exemple #8
0
    def intersect(self, **kwargs):
        """
            Intersect a Line or Point Collection and the Shoreline

            Returns the point of intersection along the coastline
            Should also return a linestring buffer around the interseciton point
            so we can calculate the direction to bounce a particle.
        """
        ls = None
        if "linestring" in kwargs:
            ls = kwargs.pop('linestring')
            spoint = Point(ls.coords[0])
            epoint = Point(ls.coords[-1])
        elif "start_point" and "end_point" in kwargs:
            spoint = kwargs.pop('start_point')
            epoint = kwargs.pop('end_point')
            ls = LineString(list(spoint.coords) + list(epoint.coords))
        else:
            raise TypeError( "must provide a LineString geometry object or (2) Point geometry objects" )

        inter = False

        # If the current point lies outside of our current shapefile index,
        # re-query the shapefile in a buffer around this point
        if self._spatial_query_object and not ls.within(self._spatial_query_object):
            self.index(point=spoint)

        for element in self._geoms:
            prepped_element = prep(element)

            # Test if starting on land
            if prepped_element.contains(spoint):
                raise Exception('Starting point on land')

            inter = ls.intersection(element)
            if inter:
                # Return the first point in the linestring, and the linestring that it hit
                if isinstance(inter, MultiLineString):
                    inter = inter.geoms[0]

                inter = Point(inter.coords[0])
                smaller_int = inter.buffer(self._spatialbuffer)
                shorelines = element.exterior.intersection(smaller_int)
                if isinstance(shorelines, LineString):
                    shorelines = [shorelines]
                else:
                    shorelines = list(shorelines)

                for shore_segment in shorelines:
                    # Once we find the linestring in the Polygon that was
                    # intersected, break out and return
                    if ls.touches(shore_segment):
                        break

                return {'point': Point(inter.x, inter.y, 0), 'feature': shore_segment or None}
        return None
class LinearReferencingTestCase(unittest.TestCase):
    def setUp(self):
        self.point = Point(1, 1)
        self.line1 = LineString(([0, 0], [2, 0]))
        self.line2 = LineString(([3, 0], [3, 6]))
        self.multiline = MultiLineString([
            list(self.line1.coords), list(self.line2.coords)
        ]) 

    def test_line1_project(self):
        self.assertEqual(self.line1.project(self.point), 1.0)
        self.assertEqual(self.line1.project(self.point, normalized=True), 0.5)

    def test_line2_project(self):
        self.assertEqual(self.line2.project(self.point), 1.0)
        self.assertAlmostEqual(self.line2.project(self.point, normalized=True),
            0.16666666666, 8)

    def test_multiline_project(self):
        self.assertEqual(self.multiline.project(self.point), 1.0)
        self.assertEqual(self.multiline.project(self.point, normalized=True),
            0.125)

    def test_not_supported_project(self):
        self.assertRaises(TypeError, self.point.buffer(1.0).project,
            self.point)

    def test_not_on_line_project(self):
        # Points that aren't on the line project to 0.
        self.assertEqual(self.line1.project(Point(-10,-10)), 0.0)

    def test_line1_interpolate(self):
        self.failUnless(self.line1.interpolate(0.5).equals(Point(0.5, 0.0)))
        self.failUnless(
            self.line1.interpolate(0.5, normalized=True).equals(
                Point(1.0, 0.0)))

    def test_line2_interpolate(self):
        self.failUnless(self.line2.interpolate(0.5).equals(Point(3.0, 0.5)))
        self.failUnless(
            self.line2.interpolate(0.5, normalized=True).equals(
                Point(3.0, 3.0)))

    def test_multiline_interpolate(self):
        self.failUnless(self.multiline.interpolate(0.5).equals(
            Point(0.5, 0.0)))
        self.failUnless(
            self.multiline.interpolate(0.5, normalized=True).equals(
                Point(3.0, 2.0)))

    def test_line_ends_interpolate(self):
        # Distances greater than length of the line or less than
        # zero yield the line's ends.
        self.failUnless(self.line1.interpolate(-1000).equals(Point(0.0, 0.0)))
        self.failUnless(self.line1.interpolate(1000).equals(Point(2.0, 0.0)))
Exemple #10
0
def access_isocrone(point_origine=(21.7351529, 41.7147303),
                    precision=0.022, size=0.35,
                    host='http://localhost:5000'):
    """
    Parameters
    ----------
    point_origine: 2-floats tuple
        The coordinates of the center point to use as (x, y).
    precision: float
        The name of the column of *gdf* containing the value to use.
    size: float
        Search radius (in degree).
    host: string, default 'http://localhost:5000'
        OSRM instance URL (no final backslash)

    Return
    ------
    gdf_ploy: GeoDataFrame
        The shape of the computed accessibility polygons.
    grid: GeoDataFrame
        The location and time of each used point.
    point_origine: 2-floats tuple
        The coord (x, y) of the origin point (could be the same as provided
        or have been slightly moved to be on a road).
    """
    from osrm import light_table, locate
    pt = Point(point_origine)
    gdf = GeoDataFrame(geometry=[pt.buffer(size)])
    grid = make_grid(gdf, precision, cut=False)
    len(grid)
    if len(grid) > 4000:
        print('Too large query requiered - Reduce precision or size')
        return -1
    point_origine = locate(point_origine, host=host)['mapped_coordinate'][::-1]
    liste_coords = [locate((i.coords.xy[0][0], i.coords.xy[1][0]), host=host)
                    ['mapped_coordinate'][::-1]
                    for i in grid.geometry.centroid]
    liste_coords.append(point_origine)
    matrix = light_table(liste_coords, host=host)
    times = matrix[len(matrix)-1].tolist()
    del matrix
    geoms, values = [], []
    for time, coord in zip(times, liste_coords):
        if time != 2147483647 and time != 0:
            geoms.append(Point(coord))
            values.append(time/3600)
    grid = GeoDataFrame(geometry=geoms, data=values, columns=['time'])
    del geoms
    del values
    collec_poly, levels = countour_poly(grid, 'time', levels=8)
    gdf_poly = isopoly_to_gdf(collec_poly, 'time', levels)
    return gdf_poly, grid, point_origine
Exemple #11
0
def line_angle_at(line, point, h=0.001):
    """
    return the angle of `line` at the `point` given. I

    If point is not in the line, return the angle at the
    nearest point within the line.
    """
    point = Point(*_normalize_point(point))
    if not line.intersects(point):
        point = nearest_point(line, point)
    bufdist = min(line.length, h)
    c = point.buffer(bufdist).exterior
    points = c.intersection(line)
    if isinstance(points, Point):
        # only one intersection, point is one of the extremes
        a = points
        b = line.intersection(point.buffer(bufdist*2).exterior)
        if not isinstance(b, Point):
            b = b[0]
    else:
        assert len(points) == 2
        a, b = points
    return angle_from_points(a.centroid, b.centroid)
Exemple #12
0
Fichier : cdl.py Projet : piw/pyCDL
def clip_route(raster, rte, resolution, bf_size=400.0):
    """
    define a function to extract CDL info based on overlay of bird survey route

    list of function parameters:
    - raster:     raster map image of CDL data (2D numpy array of float)
    - pts:        coordinates of stops along a route
    - resolution: resolution of CDL raster image, unit: degree/pixel
    - dx:         x reference of lower-left (SW) point on CDL raster map
    - dy:         y reference of upper-right (NE) point on CDL raster map
    - bf_size:    radius of buffer zone, unit: degree
    - box_size:   size of a larger box in which buffer was defined, unit: pixel
    """

    # create a (nType x nPoint) 2D array for crop counting at each stop
    # each row has nType elements, mapping to each LandType groups in CDL layer
    # it represents counts of each group within the buffer zone
    stat = np.zeros((len(LandType.cdl_group), len(rte.stops)), dtype=np.float)
    dc = int(floor(bf_size / resolution) + 2)
    half_res = resolution / 2.0

    # loop through all stops to count crops inside a buffer around each point
    for n in range(len(rte.stops)):
        p = Point(rte.stops[n][0], rte.stops[n][1])  # read Point array
        b = p.buffer(bf_size)  # create a buffer

        dx, dy = states_by_id[rte.stateID].coord
        xr, yr = (p.x - dx) % resolution, (dy - p.y) % resolution
        nx, ny = int((p.x-dx-xr) / resolution), int((dy-p.y-yr) / resolution)
        if xr > half_res:
            nx += 1
        if yr > half_res:
            ny += 1

        # loop through larger box drawn on CDL cdl layer, if a pixel falls
        # within the previously defined buffer, count the crop at this pixel
        for i in range(- dc, dc + 1):
            for j in range(- dc, dc + 1):
                cx, cy = nx + i, ny + j
                rx, ry = dx + cx * resolution, dy - cy * resolution
                cell = Polygon([(rx - half_res, ry - half_res),
                                (rx - half_res, ry + half_res),
                                (rx + half_res, ry + half_res),
                                (rx + half_res, ry - half_res)])
                if cell.intersects(b):
                    intersect = b.intersection(cell)
                    fraction = intersect.area / (resolution ** 2)
                    stat[cdl_index[raster[cy, cx]].group, n] += fraction

    return stat
    def is_on_surface(self, moveable_obj, edge_index):
        edge = self.vertices_of_edges[edge_index]

        center_x, center_y = moveable_obj.position
        gravity_vec = Line([moveable_obj.position, (center_x, 0)])
        edge_line = Line(edge).buffer(1)

        radius = moveable_obj.fixtures[0].shape.radius
        center = Point(center_x, center_y)
        circle = center.buffer(radius)
        if circle.intersects(edge_line):
            if self.is_edge_surface[edge_index] == 1 and gravity_vec.intersects(edge_line):
                return True, 0
        return False, center.distance(edge_line)   
def build_polygon(n_points, points):
    geom = []
    for p_str in points.split(' '):
        if len(p_str) > 1:
            (x, y) = p_str.lstrip().split(',')
            p = Point(int(x), int(y))
            geom.append(p.buffer(point_buffer))
    assert(len(geom) == n_points)

    polygon = cascaded_union(geom)
    if polygon.is_valid and polygon.geom_type == 'Polygon':
        return polygon.simplify(initial_simplify)
    else:
        print 'invalid polygon generated'
        sys.exit(1)
 def SpatialToplogy (Spatial_A,Spatial_B):
            if Spatial_A[4] == 'Point' and Spatial_B[4]== 'Point':
              Point_0=Point(Spatial_A[0],Spatial_A[1])
              Point_1=Point(Spatial_B[0],Spatial_B[1])
              #Point to point relationships
              if Point_0.equals(Point_1): return 'Point1 equals Point2'
              if Point_0.within(Point_1.buffer(2)): return 'Point1 lies within a buffer of 2 m from Point2'
              if Point_0.overlaps(Point_1): return 'Point1 overlaps Point2'
              #if Point_0.disjoint(Point_1): return 'Point1 disjoint Point2'
              
              #Point to line relationships
            if Spatial_A[4] == 'Point' and Spatial_B[4]== 'Line':
                 Point_0=Point(Spatial_A[0],Spatial_A[1])
                 Line_0=LineString([(Spatial_B[0],Spatial_B[1]),(Spatial_B[2],Spatial_B[3])])
                 if Point_0.touches(Line_0):return 'Point1 touches Line1'
                 if Point_0.within(Line_0.buffer(2)):return 'Point1 lies within a buffer of 2 m from L1'
              #Point to polygon relationships
            if Spatial_A[4] == 'Point' and Spatial_B[4]== 'Polygon':
                 Point_0=Point(Spatial_A[0],Spatial_A[1])
                 Polygon_0=Polygon([(Spatial_B[0],Spatial_B[1]),(Spatial_B[2],Spatial_B[1]),(Spatial_B[2],Spatial_B[3]),(Spatial_B[0],Spatial_B[3])])
                 if Point_0.touches(Polygon_0):return 'Point1 touches Polygon1'
                 if Point_0.within(Polygon_0):return'Point1 lies within Polygon1'
                 if Point_0.overlaps(Polygon_0):return 'Point1 lies overlaps Polygon1'
             #Line to line relationships
            if Spatial_A[4]=='Line' and Spatial_B[4]=='Line':
                 Line_0=LineString([(Spatial_A[0],Spatial_A[1]),(Spatial_A[2],Spatial_A[3])])
                 Line_1=LineString([(Spatial_B[0],Spatial_B[1]),(Spatial_B[2],Spatial_B[3])])
                 if Line_0.equals(Line_1):return 'Line0 equals Line1'
                 if Line_0.touches(Line_1):return 'Line0 touches Line1'
                 if Line_0.crosses(Line_1):return 'Line0 crosses Line1'
                 if Line_0.within(Line_1.buffer(2)):return 'Line0 lies within a buffer of 2 m Line1'
                 if Line_0.overlaps(Line_1):return 'Line0 overlaps Line1'
              #Line to polygon relationships  
            if Spatial_A[4]=='Line' and Spatial_B[4]=='Polygon':
                 Line_0=LineString([(Spatial_A[0],Spatial_A[1]),(Spatial_A[2],Spatial_A[3])])
                 Polygon_0=Polygon([(Spatial_B[0],Spatial_B[1]),(Spatial_B[2],Spatial_B[1]),(Spatial_B[2],Spatial_B[3]),(Spatial_B[0],Spatial_B[3])])
                 if Line_0.touches(Polygon_0):return 'Line0 touches Polygon1'
                 if Line_0.crosses(Polygon_0):return 'Line0 crosses Polygon1'
                 if Line_0.within(Polygon_0):return 'Line0 lies within Polygon1'
              #Polygon to Polygon relationships
            if Spatial_A[4]=='Polygon' and Spatial_B[4]=='Polygon':
                 Polygon_0=Polygon([(Spatial_A[0],Spatial_A[1]),(Spatial_A[2],Spatial_A[1]),(Spatial_A[2],Spatial_A[3]),(Spatial_A[0],Spatial_A[3])])
                 Polygon_1=Polygon([(Spatial_B[0],Spatial_B[1]),(Spatial_B[2],Spatial_B[1]),(Spatial_B[2],Spatial_B[3]),(Spatial_B[0],Spatial_B[3])])
                 if Polygon_0.touches(Polygon_1):return 'Polygon touches Polygon1'
                 if Polygon_0.equals(Polygon_1):return 'Polygon0 equals Polygon1'
                 if Polygon_0.within(Polygon_1):return 'Polygon lies within Polygon1'
                 if Polygon_0.within(Polygon_1.buffer(2)):return 'Polygon lies within a buffer of 2m  Polygon1'
Exemple #16
0
def nearest_point(geom, p, eps=None):
    """
    find the point in `geom` which is nearest from point `p`

    eps: epsilon
    """
    MINDIST = 1e-16
    if not isinstance(p, Point):
        p = Point(*p)
    if geom.contains(p):
        return p
    if eps is None:
        eps = geom.distance(p) * 0.0001
    dist = geom.distance(p)
    if dist < MINDIST:
        dist = 1e-12

    try:
        circunf = p.buffer(dist+eps)
        p2 = circunf.exterior.intersection(geom)
    except _TopologicalError:
        return nearest_point(geom, p, eps*3)

    if circunf.contains(geom):
        # we are probably near the centroid of the geom, inside it
        n = geom.representative_point()
        assert abs(n.distance(p) - geom.distance(p)) < 1e-3
        return n

    if p2.is_empty:
        # eps is too small, try with a larger one
        return nearest_point(geom, p, eps*6)

    if isinstance(p2, MultiPoint):
        a = p2[0]
        b = p2[1]
        p3 = linestr(a, b).centroid
    elif isinstance(p2, Polygon):
        p3 = linestr(p2.centroid, p).intersection(p2.exterior)
    elif isinstance(p2, LineString):
        p3 = p2.centroid
    elif isinstance(p2, MultiLineString):
        p3 = p2[0].centroid
    else:
        raise TypeError("other geometries not supported YET")
    assert not p3.is_empty and isinstance(p3, Point)
    return p3
Exemple #17
0
    def is_near_waypoint(self):
        """Check if the robot is near its waypoint (in distance, not rotation).

        Returns
        -------
        bool
            True if the robot is near its waypoint, false otherwise.
        """
        if self.controller_status != 'translating':
            raise RuntimeError("*is_near_waypoint* should not be called while "
                               "the robot's status is anything "
                               "but *translating*.")

        way_pt = Point(self.next_waypoint[0:2])
        approximation_circle = way_pt.buffer(self.distance_allowance)
        pose_pt = Point(self.robot.pose2D.pose[0:2])
        return approximation_circle.contains(pose_pt)
class HeadingPlan(TaskBase):
    def __init__(self, nav,
            waypoint=ll.LatLon(50.742810, 1.014469), # somewhere in the solent
            target_radius=2, waypoint_id=None,
            ):
        """Heading planning machinery, dumb version.
        
        For testing purposes, this believes that the boat can go in any
        direction, including directly upwind. It never tries to tack.
        """
        self.nav = nav
        self.waypoint = waypoint
        self.waypoint_id = waypoint_id
        x, y = self.nav.latlon_to_utm(waypoint.lat.decimal_degree, waypoint.lon.decimal_degree)
        self.waypoint_xy = Point(x, y)
        self.target_area = self.waypoint_xy.buffer(target_radius)
    
    def start(self):
        pass

    def check_end_condition(self):
        return self.nav.position_xy.within(self.target_area)

    def distance_heading_to_waypoint(self):
        dx = self.waypoint_xy.x - self.nav.position_xy.x
        dy = self.waypoint_xy.y - self.nav.position_xy.y
        d = (dx**2 + dy**2) ** 0.5
        h = math.degrees(math.atan2(dx, dy)) % 360
        return d, h

    debug_topics = [
        ('distance_to_waypoint', 'Float32'),
        ('heading_to_waypoint', 'Float32'),
        ('latest_waypoint_id', 'String'),
    ]

    def calculate_state_and_goal(self):
        """Work out what we want the boat to do
        """
        dwp, hwp = self.distance_heading_to_waypoint()
        self.debug_pub('distance_to_waypoint', dwp)
        self.debug_pub('heading_to_waypoint', hwp)
        self.debug_pub('latest_waypoint_id', self.waypoint_id)
        wp_heading = self.nav.position_ll.heading_initial(self.waypoint)
        return 'normal', wp_heading
Exemple #19
0
def create_reaches(part, segment_nodes, grid_geoms):
    """Creates SFR reaches for a segment by ordering model cells intersected by a LineString

    Parameters
    ----------
    part: LineString
        shapely LineString object (or a part of a MultiLineString)

    segment_nodes: list of integers
        Model node numbers intersected by *part*

    grid_geoms: list of Polygons
        List of shapely Polygon objects for the model grid cells, sorted by node number

    Returns
    -------
    ordered_reach_geoms: list of LineStrings
        List of LineString objects representing the SFR reaches for the segment

    ordered_node_numbers: list of model cells containing the SFR reaches for the segment
    """
    reach_geoms = [part.intersection(grid_geoms[c]) for c in segment_nodes]
    start = Point(zip(part.xy[0], part.xy[1])[0])
    end = Point(zip(part.xy[0], part.xy[1])[-1])

    ordered_reach_geoms = []
    ordered_node_numbers = []
    nreaches = len(segment_nodes)
    current_reach = start
    for i in range(nreaches):
        r = [
            j
            for j, g in enumerate(reach_geoms)
            if current_reach.intersects(g.buffer(1)) and segment_nodes[j] + 1 not in ordered_node_numbers
        ]
        if len(r) > 0:
            r = r[0]
            next_reach = reach_geoms[r]
            ordered_reach_geoms.append(next_reach)
            ordered_node_numbers.append(segment_nodes[r] + 1)
            current_reach = next_reach
        if current_reach.touches(end.buffer(1)):
            break
    return ordered_reach_geoms, ordered_node_numbers
    def to_kml(self, alpha=DEFAULT_ALPHA):
        self.init_color(alpha=alpha)
        
        ns = '{http://www.opengis.net/kml/2.2}'
        doc = kml.Document(ns, 'temp','Temps from MyTracks',
                           'Temps from MyTracks')
        folder = kml.Folder(ns, 'waypoints', 'waypoints', 'waypoints')
        doc.append(folder)

        r2p = region_points(self)
        areas = get_areas(self)
        avg_area = areas.mean(axis=0)
        area_std = areas.std(axis=0)
        for i, (ri, P) in enumerate(get_voronoi_polys(self)):
            region_poly = Polygon(P)
            center = Point(*self.points[r2p[ri][0]])
            # circle = center.buffer(np.sqrt(avg_area/np.pi))
            circle = center.buffer(avg_area*100)
            intersect = circle.intersection(region_poly)

            style_name = 'region-{}'.format(ri)
            style = kml.Style(ns, style_name)
            rstyle = kml_styles.PolyStyle(ns, color=self.region_color(ri))
            style.append_style(rstyle)
            doc.append_style(style)

            mark = kml.Placemark(
                ns, id=style_name, name=self.region_name(ri),
                description=self.region_description(ri),
                styleUrl='#{}'.format(style_name),
            )
            mark.geometry = intersect
            folder.append(mark)

            point_mark = kml.Placemark(
                ns, id=style_name, name=self.region_name(ri),
                description=self.region_description(ri),
                # styleUrl='#{}'.format(style_name),
            )
            point_mark.geometry = Point(*self.points[r2p[ri][0]])
            folder.append(point_mark)

        return doc
Exemple #21
0
    def add(self, name, location):
        """ Add a new place name and location to the index.
        """
        coord = self.locationCoordinate(location).zoomTo(self.zpixel)
        point = Point(coord.column, coord.row)
        
        # buffer the location by radius and get its bbox
        area = point.buffer(self.radius, 4)
        xmin, ymin, xmax, ymax = area.bounds

        # a list of quads that the buffered location overlaps
        quads = [quadkey(Coordinate(y, x, self.zpixel).zoomTo(self.zgroup))
                 for (x, y) in ((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin))]
        
        # store name + area shape
        for quad in set(quads):
            if quad in self.quads:
                self.quads[quad].append((name, area))
            else:
                self.quads[quad] = [(name, area)]
 def __init__(self,
              name,
              cells=None,
              wafer_r=25.5e3,
              trisize=10e3,
              cellsize=2e3,
              block_gap=0.,
              cell_gap=200.,
              doMCSearch=True,
              MCIterations=30,  # Small square cells
              doMCBlockSearch=True,
              MCBlockIterations=50,  # Large triangular blocks
              mkWidth=10,
              cellsAtEdges=False,
              symmetric_chips=True):
     Cell.__init__(self, name)
     self.wafer_r = wafer_r
     self.trisize = trisize
     self.cellsize = cellsize
     self.block_gap = block_gap
     self.cell_gap = cell_gap
     self.doMCSearch = doMCSearch
     self.MCIterations = MCIterations
     self.doMCBlockSearch = doMCBlockSearch
     self.MCBlockIterations = MCBlockIterations
     # Create a circle shape with the radius of the wafer
     circ = Point(0., 0.)
     self.waferShape = circ.buffer(wafer_r)
     self.blockOffset = (0, 0)
     self.cells = cells
     self.cell_layers = self._cell_layers()
     self._label = None
     self.upCellLattice = []
     self.downCellLattice = []
     self.upCenters = []
     self.downCenters = []
     self.upTris = []
     self.downTris = []
     self.cellsAtEdges = cellsAtEdges
     self.symmetric_chips = symmetric_chips
Exemple #23
0
def merge_dummy_branches(gdf, dummy_gdf, append_dummies=False):
    gdf.reset_index(inplace=True, drop=True)
    nodes = _get_nodes(gdf)
    for index, row in dummy_gdf.iterrows():
        #print(index)
        point = Point(row["geometry"].coords[-1])
        if nodes.distance(point).min() >= 1:
            # cut branch on point
            buffer = point.buffer(1)
            intersects_gdf = gdf[gdf["geometry"].intersects(buffer)]
            if not intersects_gdf.empty:
                branch = gdf[gdf["geometry"].intersects(buffer)].iloc[0]
                gdf_index = branch.name.copy()
                line = branch["geometry"]
                distance = line.project(point)
                line1, line2 = _cut_line(line, distance)
    
                # modify original gdf and append new line
                gdf.at[gdf_index, "geometry"] = line1
                gdf.at[gdf_index, "code"] = f"{branch['code']}_1"
    
                # modify original gdf and append new line
                branch.name =  len(gdf)
                branch["geometry"] = line2
                branch["code"] = f"{branch['code']}_2"
    
                gdf = gdf.append(branch)
                # print(gdf["code"].to_list())
                nodes = _get_nodes(gdf)
            else:
                print(f"warning {row.name} does not intersect a line")
    
    #merge the dummy_gdf and reset index
    drop_cols = [i for i in dummy_gdf if i not in gdf.columns]
    dummy_gdf.drop(columns=drop_cols, axis=1)
    if append_dummies:
        gdf = gdf.append(dummy_gdf)
    gdf.reset_index(inplace=True, drop=True)

    return gdf
Exemple #24
0
def line_splitter(line: LineString, pt: Point) -> List[LineString]:
    """Split a shapley line at a point. Return list of LineStrings split at point

    Args:
        line (LineString): Line to split
        pt ([Point]): Point to split line

    Returns:
        List(LineString): List of linestrings
    """
    # TODO: pt. inside line bounding box might be quicker.
    # line.envelope.contains(pt)
    if pt.buffer(0.000001).intersects(line):
        distance = line.project(pt)
        coords = list(line.coords)
        if distance == 0.0 or distance == line.length:
            return [line]
        for i, p in enumerate(coords):
            lim = len(coords) - 1
            pd = line.project(Point(p))
            if pd == distance:
                if i == lim:
                    return [line]
                else:
                    lines = [
                        LineString(coords[:i + 1]),
                        LineString(coords[i:])
                    ]
                return lines
            if pd > distance:
                cp = line.interpolate(distance)
                lines = [
                    LineString(coords[:i] + [(cp.x, cp.y)]),
                    LineString([(cp.x, cp.y)] + coords[i:])
                ]
                return lines
        return [line]
    else:
        return [line]
    def circle_sensor(self, bot, sensor):
        point1 = Point(bot.get_centre().x, bot.get_centre().y)

        circle = point1.buffer(sensor.get_radius())

        env_points = []

        # Identify points for all environment objects
        for env in self.__environment:
            point2 = Point(env.get_position()[0], env.get_position()[1])
            a = numpy.array(env.get_position())
            b = numpy.array((bot.get_centre().x, bot.get_centre().y))
            dist = numpy.linalg.norm(a - b)

            if dist < sensor.get_radius():
                front = bot.get_front_point()
                centre = bot.get_centre()
                p1 = (front.x - centre.x, front.y - centre.y)
                p2 = (env.get_position()[0] - centre.x,
                      env.get_position()[1] - centre.y)

                atan = math.degrees(
                    math.atan2(p1[1], p1[0]) - math.atan2(p2[1], p2[0]))

                if atan > 180:
                    atan = atan - 360
                elif atan < -180:
                    atan = atan + 360

                atan = -atan

                # Gaussian randomised
                ##                rand = random.gauss(atan, 3.5)
                ##                atan = rand

                return atan

        # Not in range
        return False
class Neuron:
    def __init__(self, gene, rmax=15):
        # from genotype
        self.id = gene[0]
        self.x = gene[1]
        self.y = gene[2]
        self.th = gene[3]
        self.ga = gene[4]
        self.gb = gene[5]
        self.l_in = gene[6]
        self.l_out = gene[7]
        # for topology
        self.loc = Point(self.x, self.y)
        self.area = self.loc.buffer(rmax)
        self.cx_in = []
        self.cx_out = []
        # for updating
        self.act = 0
        self.ot = 0
        self.gamma = self.ga
        self.wx_in = []
        self.wx_out = []
Exemple #27
0
def circle2shapelyCircle(circle, offsets=(0, 0)):
    """
    Takes a DXF circle object and discretizes it to create a shapely object.
    :type circle: dxfgrabber.entities.Circle
    :type offsets: tuple
    :return: A shapely object
    :rtype: (shapely Polygon? LinearRing?)
    """

    dx, dy = offsets

    x, y, z = circle.center
    r = circle.radius

    p = Point(x + dx, y + dy)

    # This should be turned on when a good value is agreed upon.
    # shapelyCircle = p.buffer(r, DxfConfig.CIRCLE_SEGMENTS_PER_UM)

    shapelyCircle = p.buffer(r)

    return shapelyCircle
def fixSingleLineAnnot(xp, yp, imsize):
    # code of ellipse generation is written by user ewcz as answer in this thread https://stackoverflow.com/questions/45158360/how-to-create-ellipse-shape-geometry
    newxp, newyp = [], []
    A = Point(xp[0], yp[0])
    B = Point(xp[1], yp[1])
    R = 4
    d = A.distance(B)
    S = Point(A.x + d / 2, A.y)
    alpha = math.atan2(B.y - A.y, B.x - A.x)
    C = S.buffer(d / 2)
    C = scale(C, 1, R / (d / 2))
    C = rotate(C, alpha, origin=A, use_radians=True)
    counter = 0
    for x, y in C.exterior.coords:
        # %5 to lower the size of the coordinates needed to create the ellipse to the fifth of the original
        # the equalities are to prevent us from creating coordinates outside the bounds of the pictures
        if counter % 5 == 0 and x < int(imsize['Width']) and y < int(
                imsize['Height']):
            newxp.append(int(x))
            newyp.append(int(y))
        counter += 1
    return newxp, newyp
Exemple #29
0
def inside_circle(vel):
    x = vel[0]
    y = vel[1]
    vc = []
    if (x * x) + (y * y) - (25) <= 0 and (x * x) + (y * y) - (4) >= 0:
        vc.append(x)
        vc.append(y)
        vc.append(0)
    elif (x * x) + (y * y) - (25) >= 0:
        p = Point(0, 0)
        c = p.buffer(5).boundary
        l = LineString([(0, 0), (x, y)])
        i = c.intersection(l)
        vc.append(i.x)
        vc.append(i.y)
        vc.append(0)
    elif (x * x) + (y * y) - (4) <= 0:
        vc.append(2 * cos(atan(y / x)))
        vc.append(2 * sin(atan(y / x)))
        vc.append(0)

    return vc
Exemple #30
0
class ScorePoint:
    def __init__(self,
                 coords: list,
                 value: float = 1,
                 influence_range: float = 2000):
        self.uuid = str(uuid.uuid4())
        self.value = value

        self._coords = np.array(coords)
        self._influence_range = influence_range
        self.setup()

    @property
    def type(self):
        return self.__class__.__name__

    @property
    def coords(self):
        return self._coords.tolist()

    @property
    def influence_range(self):
        return self._influence_range

    def set_coords(self, coords):
        self._coords = np.array(coords)
        self.setup()

    def set_influence_range(self, influence_range):
        self._influence_range = influence_range
        self.setup()

    def setup(self):
        self.geo = Point(self._coords)
        self.buffer = self.geo.buffer(self._influence_range)

    def compute(self, obj: FiniteCell) -> float:
        if self.buffer.intersects(obj.geo_center):
            obj._scores[self.type] += self.value
 def find_nearest_edge(self, point: Point) -> Union[NearestEdge, None]:
     """Finds the nearest edge to a given point and returns it as dictionary of edge attributes.
     """
     for radius in (35, 150, 400) + (conf.max_od_search_dist_m,):
         possible_matches_index = list(
             self.__edge_gdf.sindex.intersection(point.buffer(radius).bounds)
         )
         if possible_matches_index:
             possible_matches = self.__edge_gdf.iloc[possible_matches_index].copy()
             possible_matches['distance'] = [
                 geom.distance(point) for geom in possible_matches[E.geometry.name]
             ]
             shortest_dist = possible_matches['distance'].min()
             if shortest_dist < radius:
                 break
     if not possible_matches_index:
         self.log.error('No near edges found')
         return None
     nearest = possible_matches['distance'] == shortest_dist
     edge_id = possible_matches.loc[nearest].index[0]
     attrs = self.get_edge_attrs_by_id(edge_id)
     return NearestEdge(attrs, round(shortest_dist, 2))
Exemple #32
0
def calculate_incorrect_arc_ratio(wt):
    p = Point(0, 0)
    circle = p.buffer(1).boundary
    line1 = get_linestring(wt)
    pts_ideal = circle.intersection(get_linestring(get_ideal_weights()))
    try:
        i = circle.intersection(line1)
        if i.geoms and len(i.geoms) == 2:
            pt1 = [i.geoms[0].x, i.geoms[0].y]
            pt2 = [i.geoms[1].x, i.geoms[1].y]
            ideal1 = [pts_ideal.geoms[0].x, pts_ideal.geoms[0].y]
            angle1 = py_ang(pt1, ideal1)
            angle2 = py_ang(pt2, ideal1)
            ratio1 = min(angle2, angle1)
            ideal2 = [pts_ideal.geoms[1].x, pts_ideal.geoms[1].y]
            angle1 = py_ang(pt1, ideal2)
            angle2 = py_ang(pt2, ideal2)
            ratio2 = min(angle2, angle1)
            return (ratio1 + ratio2) / (2 * pi)
    except:
        return 1
    return 1
    def radiuspois(name, radius):
        tmptags = []
        #print radius
        lat = float(name[0])
        lon = float(name[1])
        if str(lat)[::-1].find('.') > 5 or str(lon)[::-1].find('.') > 5:
            print(lat, lon)
        nodesnum = 0
        nodeids = []
        lonswgs84, latswgs84 = pyproj.transform(wgs84, osm3857, lon, lat)
        p = Point(latswgs84, lonswgs84)
        p = p.buffer(radius)
        poly = Polygon(p.exterior)

        result = queryaround(radius, lat, lon)
        if result != 0 and result.nodes != []:
            for j in result.nodes:
                tmptags.append(j.tags)
            nodeids.append(result.node_ids)
            nodesnum += result.nodes.__len__()
        atomic_operation(poly, str((lat, lon)), tmptags, nodesnum, nodeids)
        return 0
Exemple #34
0
    def generate_query_bboxes(self):
        ''' For the differnet Remote ID checks: No, we need to generate three bounding boxes for the display provider, this method generates the 1 km diagonal length bounding box '''
        # Get center of of the bounding box that is inputted into the generator
        box = shapely.geometry.box(self.minx, self.miny, self.maxx, self.maxy)
        center = box.centroid
        self.bbox_center.append(center)
        # Transform to geographic co-ordinates to get areas
        transformer = Transformer.from_crs("epsg:4326", "epsg:3857")
        transformed_x, transformed_y = transformer.transform(center.x, center.y)
        pt = Point(transformed_x, transformed_y)
        # Now we have a point, we can buffer the point and create bounding boxes of the buffer to get the appropriate polygons, more than three boxes can be created, for the tests three will suffice.
        now = datetime.now()

        box_diagonals = [
            {'length': 150, 'name': 'zoomed_in_detail', 'timestamp_after': now + timedelta(seconds=60), 'timestamp_before': now + timedelta(seconds=90)},
            {'length': 380, 'name': "whole_flight_area", 'timestamp_after': now + timedelta(seconds=30), 'timestamp_before': now + timedelta(seconds=60)},
            {'length': 3000, 'name': 'too_large_query', 'timestamp_after': now + timedelta(seconds=10), 'timestamp_before': now + timedelta(seconds=30)}
        ]

        for box_id, box_diagonal in enumerate(box_diagonals):
            # Buffer the point with the appropriate length
            buffer = pt.buffer(box_diagonal['length'])
            buffer_bounds = buffer.bounds
            buffer_bounds_polygon = shapely.geometry.box(buffer_bounds[0], buffer_bounds[1], buffer_bounds[2], buffer_bounds[3])
            buffer_points = zip(buffer_bounds_polygon.exterior.coords.xy[0], buffer_bounds_polygon.exterior.coords.xy[1])
            proj_buffer_points = []
            # reproject back to ESPG 4326
            transformer2 = Transformer.from_crs("epsg:3857", "epsg:4326")
            for point in buffer_points:
                x = point[0]
                y = point[1]
                x, y = transformer2.transform(x, y)
                proj_buffer_points.append((x, y))

            buffered_box = Polygon(proj_buffer_points)
            # Get the bounds of the buffered box, this is the one that will will be fed to the remote ID display provider to query
            self.query_bboxes.append(QueryBoundingBox(name=box_diagonals[box_id]['name'], shape=buffered_box,
                                                      timestamp_after=box_diagonals[box_id]['timestamp_after'], timestamp_before=box_diagonals[box_id]['timestamp_before']))
def calculateGeom(row):
    """ Is passed a row containing flowline geometry. Finds the node
    in the geometry which is closest to center and then creates and 
    returns a 5m buffered polygon"""
    geom = row["geometry"]
    if geom.geom_type == "MultiLineString":
        geom = linemerge(geom)
    num_nodes = len(geom.coords)
    if not num_nodes == 2:
        # IF LINESTRING IS NOT COMPOSED OF ONLY TWO NODES, GET THE NODE IN THE MIDDLE MOST OF THE LINE
        point = Point(geom.coords[int(num_nodes/2)])
        bufferSize = 10
    else:
        #print("Two point linestring...")
        # IF TWO POINT LINESTRING, SMALL STREAM ANYWAY. TAKE THE POINT WHICH IS AT THE END OF THE LINE
        point = Point(geom.coords[-1])
        bufferSize = 5
    
    poly = point.buffer(bufferSize)
        
    #points = createPoints(poly, fac_raster_loc)
    
    return poly
def get_min_max(xp, yp):

    if len(xp) == 3:
        # code of ellipse generation is written by user ewcz as answer in this thread https://stackoverflow.com/questions/45158360/how-to-create-ellipse-shape-geometry
        newxp, newyp = [], []
        A = Point(xp[0], yp[0])
        B = Point(xp[1], yp[1])
        R = 3
        d = A.distance(B)
        S = Point(A.x + d / 2, A.y)
        alpha = math.atan2(B.y - A.y, B.x - A.x)
        C = S.buffer(d / 2)
        C = scale(C, 1, R / (d / 2))
        C = rotate(C, alpha, origin=A, use_radians=True)
        counter = 0
        for x, y in C.exterior.coords:
            if counter % 5 == 0:
                newxp.append(int(x))
                newyp.append(int(y))
            counter += 1
        xp = newxp
        yp = newyp
    return sorted(xp)[0], sorted(xp)[-1], sorted(yp)[0], sorted(yp)[-1]
Exemple #37
0
    def add(self, name, location):
        """ Add a new place name and location to the index.
        """
        coord = self.locationCoordinate(location).zoomTo(self.zpixel)
        point = Point(coord.column, coord.row)

        # buffer the location by radius and get its bbox
        area = point.buffer(self.radius, 4)
        xmin, ymin, xmax, ymax = area.bounds

        # a list of quads that the buffered location overlaps
        quads = [
            quadkey(Coordinate(y, x, self.zpixel).zoomTo(self.zgroup))
            for (x, y) in ((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax,
                                                                      ymin))
        ]

        # store name + area shape
        for quad in set(quads):
            if quad in self.quads:
                self.quads[quad].append((name, area))
            else:
                self.quads[quad] = [(name, area)]
def get_circle_json(station_dict):
    features = []
    geo_data = dict()
    for index, station_data in enumerate(list(station_dict.items())):
        station, radius, center_lat, center_lon = station_data[
            0], station_data[1][0], station_data[1][1], station_data[1][2]
        center = Point([center_lon, center_lat])
        circle = center.buffer(radius)  # Degrees Radius
        type_dict = {
            "type": "Feature",
            "id": station,
            "properties": {
                "name": station
            },
            "geometry": shapely.geometry.mapping(circle)
        }
        features.append(type_dict)
        geo_data[station] = Polygon(
            shapely.geometry.mapping(circle)['coordinates'][0])

    all_dict = {"type": "FeatureCollection", "features": features}
    state_geo = json.dumps(all_dict)
    return geo_data, state_geo
Exemple #39
0
    def _get_candidates(self, trace_point: TracePoint) -> CandidatesPerTracePoint:
        """

        :param trace_point: Observed data point
        :return:
        """
        tr_point = Point(trace_point.x, trace_point.y)

        candidate_roads = self.road_network.intersection(
            tr_point.buffer(self.observation_error)
        )
        candidates_per_trace_points = CandidatesPerTracePoint()
        for idx, (fid, candidate) in enumerate(candidate_roads.items()):

            # [REFERENCE IN PAPER - Map-Matching for Low-Sampling-Rate GPS Trajectories]
            # DEFINITION 6 (LINE SEGMENT PROJECTION): THE LINE SEGMENT PROJECTION OF A POINT 𝑝 TO A ROAD SEGMENT
            # 𝑒 IS THE POINT 𝑐 ON 𝑒 SUCH THAT 𝑐 = ARG 𝑚𝑖𝑛∀ 𝑐𝑖∈𝑒 𝑑𝑖𝑠𝑡(𝑐𝑖, 𝑝) , WHERE 𝑑𝑖𝑠𝑡(𝑐𝑖, 𝑝) RETURNS THE DISTANCE
            # BETWEEN P AND ANY POINT CI ON 𝑒.

            # PROJECT THE POINT ON THE ALL THE ROAD SEGMENT THAT LIE IN THE BUFFER ZONE OF - 30 AND GET THE
            # POINT ON THE LINE WITH SHORTEST DISTANCE TO THE TRACE_REC

            # https://stackoverflow.com/questions/24415806/coordinates-of-the-closest-points-of-two-geometries-in-shapely
            fraction, project_point = line_referencing(candidate, tr_point)

            # https://gist.github.com/href/1319371
            # https://stackoverflow.com/questions/35282222/in-python-how-do-i-cast-a-class-object-to-a-dict/35282286
            candidates_per_trace_points.add(
                candidate_id=str(trace_point.trace_point_id) + "_" + str(idx),
                x=project_point.x,
                y=project_point.y,
                distance=fraction,
                road_information=self.road_network.entry(fid),
                trace_information=trace_point,
            )

        return candidates_per_trace_points
Exemple #40
0
def cutOutline(point, linestring, segmentLimit=None, tolerance=pcbnew.FromMM(0.001)):
    """
    Given a point finds an entity in (multi)linestring which goes through the
    point.

    It is possible to restrict the number of segments used by specifying
    segmentLimit.

    When segment limit is passed, return a tuple of the string starting and
    ending in that point. When no limit is passed returns a single string.
    """
    if not isinstance(point, Point):
        point = Point(point[0], point[1])
    if isinstance(linestring, LineString):
        geom = [linestring]
    elif isinstance(linestring, MultiLineString):
        geom = linestring.geoms
    else:
        raise RuntimeError("Unknown geometry '{}' passed".format(type(linestring)))
    for string in geom:
        bufferedPoint = point.buffer(tolerance, resolution=1)
        splitted = split(string, bufferedPoint)
        if len(splitted) == 1 and not Point(splitted[0].coords[0]).intersects(bufferedPoint):
            continue
        if len(splitted) == 3:
            string = LineString([point] + list(splitted[2].coords) + splitted[0].coords[1:])
        elif len(splitted) == 2:
            string = LineString(list(splitted[1].coords) + splitted[0].coords[1:])
        else:
            string = splitted[0]
        if segmentLimit is None:
            return string
        limit1 = max(1, len(string.coords) - segmentLimit)
        limit2 = min(segmentLimit, len(string.coords) - 1)
        return LineString(string.coords[limit1:]), LineString(string.coords[:limit2])
    return None, None
def getGeom(code, lon, lat):
    tmp_pnt = Point(lon, lat)

    if not inCountry(tmp_pnt):
        print("point not in country")
        return 0

    elif lookup[code]["type"] == "point":
        return tmp_pnt

    elif lookup[code]["type"] == "buffer":
        try:
            tmp_int = float(lookup[code]["data"])
            tmp_buffer = tmp_pnt.buffer(tmp_int)

            if inCountry(tmp_buffer):
                return tmp_buffer
            else:
                return tmp_buffer.intersection(adm0)

        except:
            print("buffer value could not be converted to float")
            return 0

    elif lookup[code]["type"] == "adm":
        try:
            tmp_int = int(lookup[code]["data"])
            return getPolyWithin(tmp_pnt, adm_shps[tmp_int])

        except:
            print("adm value could not be converted to int")
            return 0

    else:
        print("code type not recognized")
        return 0
Exemple #42
0
    def testMerger(self):
        # build chunks for the polygons
        tile_box = box(0, 0, 512, 256)  # a box having the same dimension as the tile
        circle = Point(600, 360)
        circle = circle.buffer(250)

        circle_part1 = tile_box.intersection(circle)
        circle_part2 = translate(tile_box, xoff=512).intersection(circle)
        circle_part3 = translate(tile_box, yoff=256).intersection(circle)
        circle_part4 = translate(tile_box, xoff=512, yoff=256).intersection(circle)
        circle_part5 = translate(tile_box, yoff=512).intersection(circle)
        circle_part6 = translate(tile_box, xoff=512, yoff=512).intersection(circle)

        # create topology
        fake_image = FakeImage(1024, 768, 3)
        fake_builder = FakeTileBuilder()
        topology = fake_image.tile_topology(fake_builder, 512, 256)

        tile1 = topology.tile(1)
        tile2 = topology.tile(2)
        tile3 = topology.tile(3)
        tile4 = topology.tile(4)
        tile5 = topology.tile(5)
        tile6 = topology.tile(6)

        tiles = [tile1.identifier, tile2.identifier, tile3.identifier, tile4.identifier, tile5.identifier, tile6.identifier]
        tile_polygons = [[circle_part1], [circle_part2], [circle_part3], [circle_part4], [circle_part5], [circle_part6]]

        polygons = SemanticMerger(5).merge(tiles, tile_polygons, topology)
        self.assertEqual(len(polygons), 1, "Number of found polygon")

        # use recall and false discovery rate to evaluate the error on the surface
        tpr = circle.difference(polygons[0]).area / circle.area
        fdr = polygons[0].difference(circle).area / polygons[0].area
        self.assertLessEqual(tpr, 0.002, "Recall is low for circle area")
        self.assertLessEqual(fdr, 0.002, "False discovery rate is low for circle area")
Exemple #43
0
def checkCoordinates_in_animalInfo(latitude, longitude, animal_boundary,
                                   search_radius):

    # create a polygon object originating from the latitude and longitude
    origin_point = Point(latitude, longitude)

    # Create a circle that will be where we search for animal habitats
    search_area = origin_point.buffer(search_radius)

    # Turn this circle into a polygon object that can be used to check if it
    # intersects with an animal's polygon object that represents its habitat
    search_polygon = Polygon(list(search_area.exterior.coords))

    # Otherwise, check if our search area intersects with the animal's habitat
    for boundary in animal_boundary:

        # Check if any of the animal boundaries intersect with the search area
        if search_polygon.intersects(boundary):

            # If one does intersect, return true
            return True

    # If none of the boundaries intersected, then return false
    return False
Exemple #44
0
class Contamination(Attractor):
    """
	Used in contamination removal scenarios
	Contamination begins at a hotspot and grows in all directions
	Robots at the perimeter can slow down/reduce the spread
	"""
    def __init__(self, position, radius):
        """
		Args:
			position: tuple (x,y)
			radius
		"""
        super().__init__(Point(*position).buffer(radius))
        self.radius = radius
        self.pos = Point(*position)
        self.subtype = 'contamination'

    def update(self, increment=1, rate=0.005):
        """
		Increment can be positive or negative
		Radius change is proportional to area and incerment
		"""
        self.radius += increment * rate / (self.radius**2)
        self.polygon = self.pos.buffer(self.radius)
Exemple #45
0
def fleur_de_lys(H,e):
    sinpi4=math.sin(math.pi/6)
    cospi4=math.cos(math.pi/6)
    sinpi6=math.sin(math.pi/12)
    cospi6=math.cos(math.pi/12)
    A = Point (-H*0.3*cospi4, H*0.0-H*0.3*sinpi4)
    B = Point ( H*0.3*cospi4, H*0.0-H*0.3*sinpi4)
    C = Point (-H*0.3*cospi6, H*0.0-H*0.3*sinpi6)
    D = Point ( H*0.3*cospi6, H*0.0-H*0.3*sinpi6)
    E = Point (H*0.5,  H*0.5)
    F = Point (-H*0.5, H*0.5)
    C1 = E.buffer(H*0.5+e*0.5)
    C2 = F.buffer(H*0.5+e*0.5)
    C3 = A.buffer(H*0.3)
    C4 = B.buffer(H*0.3)
    C5 = C.buffer(H*0.3)
    C6=  D.buffer(H*0.3)
    left = C5.difference(C3)
    right = C6.difference(C4)
    top = C1.intersection(C2)
    shape = left.union(top)
    shape = shape.union(right)
    return shape
    if str(polygon_name) in keep_dict:
        keep_dict[str(polygon_name)] += 1
        tag_name_dict[str(polygon_name)].append(key)
    else:
        keep_dict[str(polygon_name)] = 1
        tag_name_dict[str(polygon_name)] = [key]

#print "Polygon Count Of Tags"
#for key,value in keep_dict.items():
#	print " Value:"+str(value)

k = 5
for radius in range(1, 12):
    total_tags = []
    radi = radius * 100
    circle = query_point.buffer(radi)
    ration_value = 0
    total_tags_detected = 0
    total_polygons = polygon_set
    dict3 = keep_dict

    for poly in total_polygons:
        if circle.intersects(poly):
            # list_of_points=dict3[poly]
            no_of_tags = 0
            if str(poly) in dict3.keys():
                no_of_tags = dict3[str(poly)]
                print "no. of tags detected"
                print no_of_tags
                # dict3[str(powerlevelpoly)]+=1
                total_tags_detected += no_of_tags
Exemple #47
0
def z_level_gpd(x, y, g_array, radius):
    # for geopandas array
    s = Point(x, y)  # используем уточненную координату
    grd_cut2 = g_array[g_array.within(s.buffer(radius))]  # вырезаем поуже
    return np.mean(grd_cut2['z'])  # новый уровень земли
Exemple #48
0
class LinearReferencingTestCase(unittest.TestCase):

    def setUp(self):
        self.point = Point(1, 1)
        self.line1 = LineString(([0, 0], [2, 0]))
        self.line2 = LineString(([3, 0], [3, 6]))
        self.multiline = MultiLineString([
            list(self.line1.coords), list(self.line2.coords)
        ])

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_line1_project(self):
        self.assertEqual(self.line1.project(self.point), 1.0)
        self.assertEqual(self.line1.project(self.point, normalized=True), 0.5)

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_line2_project(self):
        self.assertEqual(self.line2.project(self.point), 1.0)
        self.assertAlmostEqual(
            self.line2.project(self.point, normalized=True), 0.16666666666, 8)

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_multiline_project(self):
        self.assertEqual(self.multiline.project(self.point), 1.0)
        self.assertEqual(
            self.multiline.project(self.point, normalized=True), 0.125)

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_not_supported_project(self):
        with self.assertRaises(TypeError):
            self.point.buffer(1.0).project(self.point)

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_not_on_line_project(self):
        # Points that aren't on the line project to 0.
        self.assertEqual(self.line1.project(Point(-10, -10)), 0.0)

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_line1_interpolate(self):
        self.assertTrue(self.line1.interpolate(0.5).equals(Point(0.5, 0.0)))
        self.assertTrue(
            self.line1.interpolate(0.5, normalized=True).equals(Point(1, 0)))

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_line2_interpolate(self):
        self.assertTrue(self.line2.interpolate(0.5).equals(Point(3.0, 0.5)))
        self.assertTrue(
            self.line2.interpolate(0.5, normalized=True).equals(Point(3, 3)))

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_multiline_interpolate(self):
        self.assertTrue(self.multiline.interpolate(0.5).equals(Point(0.5, 0)))
        self.assertTrue(
            self.multiline.interpolate(0.5, normalized=True).equals(
                Point(3.0, 2.0)))

    @unittest.skipIf(geos_version < (3, 2, 0), 'GEOS 3.2.0 required')
    def test_line_ends_interpolate(self):
        # Distances greater than length of the line or less than
        # zero yield the line's ends.
        self.assertTrue(self.line1.interpolate(-1000).equals(Point(0.0, 0.0)))
        self.assertTrue(self.line1.interpolate(1000).equals(Point(2.0, 0.0)))
class HeadingPlan:
    def __init__(self, nav, tack_line_offset=0.01,
            waypoint=ll.LatLon(50.742810, 1.014469), # somewhere in the solent
            target_radius=2,
            ):
        """Heading planning machinery.

        beating_angle is the closest angle we can sail to the wind -
        the total dead zone is twice this angle. Measured in degrees.

        tack_line_offset is half the width of the tacking corridor we use when
        sailing towards a marker upwind, measured in km.
        
        utm_zone is the zone number of the UTM system to use. Southampton is in
        zone 30, Portugal in zone 29. http://www.dmap.co.uk/utmworld.htm
        Distance calculations will be less accurate the further from the
        specified zone you are.
        """
        self.nav = nav
        self.waypoint = waypoint
        x, y = self.nav.latlon_to_utm(waypoint.lat.decimal_degree, waypoint.lon.decimal_degree)
        self.waypoint_xy = Point(x, y)
        self.target_area = self.waypoint_xy.buffer(target_radius)
        self.tack_line_offset = tack_line_offset
        self.wp_heading = 0
        self.side_heading = 0
        self.alternate_heading = 0
        self.sailing_state = 'normal'  # sailing state can be 'normal','tack_to_port_tack' or  'tack_to_stbd_tack'
    
    def start(self):
        pass

    def check_end_condition(self):
        return self.nav.position_xy.within(self.target_area)

    def distance_heading_to_waypoint(self):
        dx = self.waypoint_xy.x - self.nav.position_xy.x
        dy = self.waypoint_xy.y - self.nav.position_xy.y
        d = (dx**2 + dy**2) ** 0.5
        h = math.degrees(math.atan2(dx, dy)) % 360
        return d, h

    def calculate_state_and_goal(self):
        """Work out what we want the boat to do
        """
        boat_wind_angle = self.nav.angle_to_wind()
        if self.sailing_state != 'normal':
            # A tack is in progress
            if self.sailing_state == 'tack_to_port_tack':
                beating_angle = self.nav.beating_angle
                continue_tack = boat_wind_angle < beating_angle
            else:  # 'tack_to_stbd_tack'
                beating_angle = -self.nav.beating_angle
                continue_tack = boat_wind_angle > beating_angle
            if continue_tack:
                return self.sailing_state, self.nav.wind_angle_to_heading(beating_angle)
            else:
                # Tack completed
                self.sailing_state = 'normal'

        # We're not tacking right now - where do we want to go?
        wp_heading = self.nav.position_ll.heading_initial(self.waypoint)
        wp_wind_angle = self.nav.heading_to_wind_angle(wp_heading)
        if abs(wp_wind_angle) > self.nav.beating_angle:
            # We can sail directly for the next waypoint
            if (wp_wind_angle * boat_wind_angle) > 0:
                # These two have the same sign, so we're on the right tack.
                return ('normal', wp_heading)
            else:
                # We need to tack before going to the waypoint
                if wp_wind_angle > 0:
                    switch_to = 'tack_to_port_tack'
                    beating_angle = self.nav.beating_angle
                else:
                    switch_to = 'tack_to_stbd_tack'
                    beating_angle = -self.nav.beating_angle
                self.sailing_state = switch_to
                return switch_to, self.nav.wind_angle_to_heading(beating_angle)

        # We need to tack upwind to the waypoint.
        if boat_wind_angle > 0:
            # On the port tack
            offset_hdg = angleSum(self.nav.absolute_wind_direction(), 90)
            beating_angle = self.nav.beating_angle
            other_tack = 'tack_to_stbd_tack'
        else:
            offset_hdg = angleSum(self.nav.absolute_wind_direction(), -90)
            beating_angle = -self.nav.beating_angle
            other_tack = 'tack_to_port_tack'
        tack_point = self.waypoint.offset(offset_hdg, self.tack_line_offset)
        boat_from_tack_pt = tack_point.heading_initial(self.nav.position_ll)
        if angleAbsDistance(boat_from_tack_pt, offset_hdg) < 90:
            # Outside the tack corridor. Ready about!
            self.sailing_state = other_tack
            return other_tack, self.nav.wind_angle_to_heading(-beating_angle)
        else:
            # Continue on this tack, sailing as close to the wind as we can.
            return 'normal', self.nav.wind_angle_to_heading(beating_angle)
__author__ = 'matt'
"""
Objective: Convert output from shapely (WKT) to GeoJSON
"""

from shapely.geometry import Point
from vectorformats.Formats import GeoJSON, WKT

# Create Shapely Geometry and Buffer
p1 = Point(10,10)
p1buff = p1.buffer(10)

## Create New Instance of WKT Class
#wkt1 = WKT.WKT()
## Decode WKT of Buffer to a vectorformats feature
#wkt1_decoded = wkt1.decode(p1buff.to_wkt())
## Create New Instance of GeoJSON Class
#geojson1 = GeoJSON.GeoJSON()
## Re-encode WKT decoded features as GeoJSON
#print geojson1.encode(wkt1_decoded, to_string=True)

def wkt_to_geojson(wktStr):
    """Return GeoJSON from a WKT string."""
    # Create instances of vectorfeatures WKT/GeoJSON Classes
    inWKT = WKT.WKT()
    outGeoJSON = GeoJSON.GeoJSON()
    # Decode WKT to vectorformats features, and re-encode as GeoJSON
    return outGeoJSON.encode(inWKT.decode(wktStr), to_string=True)

print wkt_to_geojson(p1buff.to_wkt())
                           (-2.75, 3.75)])
    rectangle_3 = Polygon([(4.75, -0.75), (3.25, -0.75), (3.25, 0.75),
                           (4.75, 0.75)])

    if point.distance(rectangle_1) <= radius + clearance:
        flag = 1

    if point.distance(rectangle_2) <= radius + clearance:
        flag = 1

    if point.distance(rectangle_3) <= radius + clearance:
        flag = 1

    # creating circles
    p1 = Point(0, 0)
    circle_1 = p1.buffer(1.0)
    p2 = Point(-2, -3)
    circle_2 = p2.buffer(1.0)
    p3 = Point(2, -3)
    circle_3 = p3.buffer(1.0)
    p4 = Point(2, 3)
    circle_4 = p4.buffer(1.0)

    if point.distance(circle_1) <= radius + clearance:
        flag = 1
    if point.distance(circle_2) <= radius + clearance:
        flag = 1
    if point.distance(circle_3) <= radius + clearance:
        flag = 1
    if point.distance(circle_4) <= radius + clearance:
        flag = 1
# -*- coding: utf-8 -*-
print('=' * 40)
print(__file__)
from helper.textool import get_tmp_file

################################################################################
from shapely.geometry import Point
Point(0, 0).geom_type

################################################################################
Point(0, 0).distance(Point(1, 1))

################################################################################
donut = Point(0, 0).buffer(2.0).difference(Point(0, 0).buffer(1.0))
donut.centroid.wkt
donut.representative_point().wkt

################################################################################
from shapely.geometry import Point
point = Point(10, 10)
pt_buf = point.buffer(5)
pt_buf.wkt
def linearize(info, pos, t_start, t_stop, expand_by=6):
    """Finds linear and zones for ideal trajectories.

        Parameters
        ----------
        info : module
            Contains session-specific information.
        pos : dict
            With x, y, time as keys. Each value is a np.array.
        t_start : float
        t_stop : float
        expand_by : int or float
            This is how much you wish to expand the line to fit
            the animal's actual movements. Default is set to 6.

        Returns
        -------
        linear : dict
            With u, shortcut, novel keys. Each value is a unique
            Shapely LineString object.
        zone : dict
            With 'ushort', 'u', 'novel', 'uped', 'unovel', 'pedestal',
            'novelped', 'shortcut', 'shortped' keys.
            Each value is a unique Shapely Polygon object.

        """
    # Slicing position to only Phase 3
    t_start_idx = vdm.find_nearest_idx(pos['time'], t_start)
    t_end_idx = vdm.find_nearest_idx(pos['time'], t_stop)
    sliced_pos = dict()
    sliced_pos['x'] = pos['x'][t_start_idx:t_end_idx]
    sliced_pos['y'] = pos['y'][t_start_idx:t_end_idx]
    sliced_pos['time'] = pos['time'][t_start_idx:t_end_idx]

    u_line = LineString(info.u_trajectory)
    shortcut_line = LineString(info.shortcut_trajectory)
    novel_line = LineString(info.novel_trajectory)

    u_start = Point(info.u_trajectory[0])
    u_stop = Point(info.u_trajectory[-1])
    shortcut_start = Point(info.shortcut_trajectory[0])
    shortcut_stop = Point(info.shortcut_trajectory[-1])
    novel_start = Point(info.novel_trajectory[0])
    novel_stop = Point(info.novel_trajectory[-1])
    pedestal_center = Point(info.path_pts['pedestal'][0], info.path_pts['pedestal'][1])
    pedestal = pedestal_center.buffer(expand_by*2.2)

    def expand_line(start_pt, stop_pt, line, expand_by):
        line_expanded = line.buffer(expand_by)
        zone = start_pt.union(line_expanded).union(stop_pt)
        return zone

    zone = dict()
    zone['u'] = expand_line(u_start, u_stop, u_line, expand_by)
    zone['shortcut'] = expand_line(shortcut_start, shortcut_stop, shortcut_line, expand_by)
    zone['novel'] = expand_line(novel_start, novel_stop, novel_line, expand_by)
    zone['ushort'] = zone['u'].intersection(zone['shortcut'])
    zone['unovel'] = zone['u'].intersection(zone['novel'])
    zone['uped'] = zone['u'].intersection(pedestal)
    zone['shortped'] = zone['shortcut'].intersection(pedestal)
    zone['novelped'] = zone['novel'].intersection(pedestal)
    zone['pedestal'] = pedestal

    u_idx = []
    shortcut_idx = []
    novel_idx = []
    other_idx = []
    for pos_idx in range(len(sliced_pos['time'])):
        point = Point([sliced_pos['x'][pos_idx], sliced_pos['y'][pos_idx]])
        if zone['u'].contains(point) or zone['ushort'].contains(point) or zone['unovel'].contains(point):
            u_idx.append(pos_idx)
        elif zone['shortcut'].contains(point) or zone['shortped'].contains(point):
            shortcut_idx.append(pos_idx)
        elif zone['novel'].contains(point) or zone['novelped'].contains(point):
            novel_idx.append(pos_idx)
        else:
            other_idx.append(pos_idx)

    u_pos = vdm.idx_in_pos(sliced_pos, u_idx)
    shortcut_pos = vdm.idx_in_pos(sliced_pos, shortcut_idx)
    novel_pos = vdm.idx_in_pos(sliced_pos, novel_idx)
    other_pos = vdm.idx_in_pos(sliced_pos, other_idx)

    linear = dict()
    linear['u'] = vdm.linear_trajectory(u_pos, u_line, t_start, t_stop)
    linear['shortcut'] = vdm.linear_trajectory(shortcut_pos, shortcut_line, t_start, t_stop)
    linear['novel'] = vdm.linear_trajectory(novel_pos, novel_line, t_start, t_stop)

    return linear, zone
from shapely.geometry import Point

# Create a Point
p1 = Point(10,10)
print p1

# According to Docs, this should work
# And should create a copy of the input point
p2 = Point(p1)
print p2

# Testing copy
p1 = Point(55,55)

print p1
print p2

for i in ['x','y','z']:
    # z is not set, should raise DimensionError based on code in point class
    try:
        print getattr(p1, i)
    except Exception, e:
        print e
        pass

# Yes you can create an empty point

p3 = Point(10,10)
p3.buffer(10).area
Exemple #55
0
    def set_agents(self,
                   size=None,
                   surface=None,
                   position="random",
                   velocity=None,
                   orientation=None,
                   target_direction="auto",
                   target_angle="auto"):
        """Set spatial and rotational parameters.

        ================== ==========================
        **kwargs**

        *size*             Integer: Number of agent to be placed. \n
                           None: Places all agents

        *surface*          surface: Custom value \n
                           None: Domain

        *position*         ndarray: Custom values \n
                           "random": Uses Monte Carlo method to place agent
                           without overlapping with obstacles or other agents.

        *target_direction* ndarray: Custom value \n
                           "random": Uniformly distributed random value \n
                           "auto":
                           None: Default value

        *velocity*         ndarray: Custom value  \n
                           "random: Uniformly distributed random value, \n
                           "auto":
                           None: Default value

        *target_angle*     ndarray: Custom value  \n
                           "random": Uniformly distributed random value, \n
                           "auto":
                           None: Default value

        *orientation*      float: Custom value  \n
                           "random": Uniformly distributed random value, \n
                           "auto":
                           None: Default value
        ================== ==========================
        """
        self.logger.info("")

        iterations = 0  # Number of iterations
        area_filled = 0  # Total area filled by agents
        random_sample = PolygonSample(surface)

        self._occupied = cascaded_union(self.obstacles + self.exits)

        start_index = self._index
        limit = start_index + size
        iter_limit = size * 50

        @numba.jit(nopython=True)
        def agent_distance_condition(agent, start_index, i):
            """Test function for determining if agents are overlapping."""
            condition = True
            if agent.three_circle:
                for j in range(start_index, i):
                    if condition:
                        t = agent_agent_distance_three_circle(agent, i, j)
                        condition &= t[1] > 0
                    else:
                        break
            else:
                for j in range(start_index, i):
                    if condition:
                        d = agent.position[i] - agent.position[j]
                        s = length(d) - agent.radius[i] - agent.radius[j]
                        condition &= s > 0
                    else:
                        break
            return condition

        while self._index < limit and iterations < iter_limit:
            # Random point inside spawn surface. Center of mass for an agent.
            if position == "random":
                point = random_sample.draw()
                self.agent.position[self._index] = np.asarray(point)
            elif isinstance(position, np.ndarray):
                point = Point(position[self._index])
                self.agent.position[self._index] = position[self._index]
            else:
                raise ValueError()

            self.set_motion(self._index, target_direction, target_angle,
                            velocity, orientation)

            # Geometry of the agent
            if self.agent.three_circle:
                self.agent.update_shoulder_position(self._index)

                point_ls = Point(self.agent.position_ls[self._index])
                point_rs = Point(self.agent.position_rs[self._index])
                agent = cascaded_union((
                    point.buffer(self.agent.r_t[self._index]),
                    point_ls.buffer(self.agent.r_s[self._index]),
                    point_rs.buffer(self.agent.r_s[self._index]),
                ))
            else:
                agent = point.buffer(self.agent.radius[self._index])

            # Check if agent intersects with other agents or obstacles
            if agent_distance_condition(self.agent, start_index, self._index) \
                    and not agent.intersects(self._occupied):
                density = area_filled / surface.area
                self.logger.debug("Agent {} | Density {}".format(
                    self._index, density))
                area_filled += agent.area
                self.agent.active[self._index] = True
                self._index += 1
            else:
                # Reset
                self.agent.position[self._index] = 0
                self.agent.position_ls[self._index] = 0
                self.agent.position_rs[self._index] = 0
                self.agent.velocity[self._index] = 0
                self.agent.angle[self._index] = 0
                self.agent.target_angle[self._index] = 0
                self.agent.target_direction[self._index] = 0
                self.agent.front[self._index] = 0

            iterations += 1

        self.logger.info("Density: {}".format(area_filled / surface.area))
Exemple #56
0
 def construct_torus(self):
     point = Point(0, 0)
     return point.buffer(5).symmetric_difference(point.buffer(2.5))
Exemple #57
0
class HeadingPlan(TaskBase):
    # For calculations, lay lines don't extend to infinity.
    # This is in m; 10km should be plenty for our purposes.
    LAYLINE_EXTENT = 10000

    def __init__(
            self,
            nav,
            waypoint=ll.LatLon(50.742810, 1.014469),  # somewhere in the solent
            target_radius=4,
            tack_voting_radius=5,
            waypoint_id='',
            name='',
            *args,
            **kwargs):
        """Sail towards a waypoint.

        *nav* is a sailing_robot.navigation.Navigation instance.

        *waypoint* is a LatLon object telling us where to go.

        *target_radius* is how close we need to get to the waypoint, in metres.

        *tack_voting_radius* is the distance within which we use tack voting, to
        avoid too frequent tacks close to the waypoint.
        """
        self.nav = nav
        self.waypoint = waypoint
        self.waypoint_xy = Point(
            self.nav.latlon_to_utm(waypoint.lat.decimal_degree,
                                   waypoint.lon.decimal_degree))
        self.target_radius = target_radius
        self.target_area = self.waypoint_xy.buffer(target_radius)
        self.sailing_state = 'normal'  # sailing state can be 'normal','switch_to_port_tack' or  'switch_to_stbd_tack'
        self.tack_voting = TackVoting(50, 35)
        self.tack_voting_radius = tack_voting_radius
        self.waypoint_id = waypoint_id
        self.name = name
        self.debug_topics = [
            ('dbg_heading_to_waypoint', 'Float32'),
            ('dbg_distance_to_waypoint', 'Float32'),
            ('dbg_goal_wind_angle', 'Float32'),
            ('dbg_latest_waypoint_id', 'String'),
        ]

    def update_waypoint(self, waypoint, waypoint_id=None):
        self.waypoint = waypoint
        self.waypoint_id = waypoint_id
        self.waypoint_xy = Point(
            self.nav.latlon_to_utm(self.waypoint.lat.decimal_degree,
                                   self.waypoint.lon.decimal_degree))
        self.target_area = self.waypoint_xy.buffer(self.target_radius)

    def update_target_radius(self, target_radius):
        self.target_radius = target_radius
        self.target_area = self.waypoint_xy.buffer(self.target_radius)

    def check_end_condition(self):
        """Are we there yet?"""
        return self.nav.position_xy.within(self.target_area)

    def calculate_state_and_goal(self):
        """Work out what we want the boat to do
        """
        dwp, hwp = self.nav.distance_and_heading(self.waypoint_xy)
        self.debug_pub('dbg_distance_to_waypoint', dwp)
        self.debug_pub('dbg_heading_to_waypoint', hwp)
        self.debug_pub('dbg_latest_waypoint_id', self.waypoint_id)
        #rospy.logwarn('111')

        boat_wind_angle = self.nav.angle_to_wind()
        #rospy.logwarn(boat_wind_angle)
        #rospy.logwarn(self.nav.beating_angle)

        wp_wind_angle = self.nav.heading_to_wind_angle(hwp)  #120
        #rospy.logwarn('qqq'+str(wp_wind_angle))
        #rospy.logwarn('www'+str(self.nav.absolute_wind_direction()))
        # Detect if the waypoint is downwind, if so head directly to it

        if abs(wp_wind_angle) > 90 or True:
            goal_wind_angle = wp_wind_angle
            self.debug_pub('dbg_goal_wind_angle', goal_wind_angle)
            state = 'normal'

            return state, hwp

        if self.sailing_state != 'normal':

            # A tack/jibe is in progress
            if self.sailing_state == 'switch_to_port_tack':
                goal_angle = self.nav.beating_angle
                continue_tack = boat_wind_angle < goal_angle or boat_wind_angle > 120

            else:  # 'switch_to_stbd_tack'
                goal_angle = -self.nav.beating_angle
                continue_tack = boat_wind_angle > goal_angle or boat_wind_angle < -120

            if continue_tack:
                self.debug_pub('dbg_goal_wind_angle', goal_angle)
                return self.sailing_state, self.nav.wind_angle_to_heading(
                    goal_angle)
            else:
                # Tack completed
                self.log('info', 'Finished tack (%s)', self.sailing_state)
                self.tack_voting.reset(boat_wind_angle > 0)
                self.sailing_state = 'normal'

        on_port_tack = boat_wind_angle > 0
        """
        wp_wind_angle = self.nav.heading_to_wind_angle(120)
        rospy.logwarn('qqq'+str(wp_wind_angle))
        rospy.logwarn('www'+str(self.nav.absolute_wind_direction()))
        # Detect if the waypoint is downwind, if so head directly to it
      
        if abs(wp_wind_angle) > 90 :
            goal_wind_angle = wp_wind_angle
            self.debug_pub('dbg_goal_wind_angle', goal_wind_angle)
            state = 'normal'
           
            return state, hwp
        """
        tack_now = True
        if wp_wind_angle * boat_wind_angle > 0:
            # These two have the same sign, so we're on the better tack already
            self.tack_voting.vote(on_port_tack)
        elif self.nav.position_xy.within(self.lay_triangle()):
            # We're between the laylines; stick to our current tack for now
            self.tack_voting.vote(on_port_tack)
        else:
            tack_now = True
            self.tack_voting.vote(not on_port_tack)

        if dwp < self.tack_voting_radius:
            # Close to the waypoint, use tack voting so we're not constantly
            # tacking.
            tack_now = self.tack_voting.tack_now(on_port_tack)

        if tack_now:
            # Ready about!
            if on_port_tack:
                state = 'switch_to_stbd_tack'
                goal_wind_angle = -self.nav.beating_angle
            else:
                state = 'switch_to_port_tack'
                goal_wind_angle = self.nav.beating_angle
            self.sailing_state = state
            self.log('info', 'Starting tack/jibe (%s)', state)
        else:
            # Stay on our current tack
            if on_port_tack:
                goal_wind_angle = max(wp_wind_angle, self.nav.beating_angle)
            else:
                goal_wind_angle = min(wp_wind_angle, -self.nav.beating_angle)
            state = 'normal'

        self.debug_pub('dbg_goal_wind_angle', goal_wind_angle)
        return state, self.nav.wind_angle_to_heading(goal_wind_angle)

    def lay_triangle(self):
        """Calculate the lay lines for the current waypoint.

        This returns a shapely Polygon with the two lines extended to
        LAYLINE_EXTENT (10km).
        """
        downwind = angleSum(self.nav.absolute_wind_direction(), 180)
        x0, y0 = self.waypoint_xy.x, self.waypoint_xy.y
        l1 = math.radians(angleSum(downwind, -self.nav.beating_angle))
        x1 = x0 + (self.LAYLINE_EXTENT * math.sin(l1))
        y1 = y0 + (self.LAYLINE_EXTENT * math.cos(l1))
        l2 = math.radians(angleSum(downwind, self.nav.beating_angle))
        x2 = x0 + (self.LAYLINE_EXTENT * math.sin(l2))
        y2 = y0 + (self.LAYLINE_EXTENT * math.cos(l2))
        return Polygon([(x0, y0), (x1, y1), (x2, y2)])
fig = pylab.figure(figsize=(24, 12), dpi=180)

for state in states:
    if state.geom_type == 'Polygon':
        state = [state]

    for poly in state:
        if ls.intersects(poly):
            alpha = 0.4
        else:
            alpha = 0.4

        try:
            poly_patch = PolygonPatch(poly, fc="#6699cc", ec="#6699cc", alpha=alpha, zorder=2)
            fig.gca().add_patch(poly_patch)
        except:
            pass

fig.gca().plot(*ls.xy, color='#FFFFFF')

for x, y in path:
    p = Point(x, y)
    spot = p.buffer(.1)
    x, y = spot.exterior.xy
    pylab.fill(x, y, color='#cc6666', aa=True)
    pylab.plot(x, y, color='#cc6666', aa=True, lw=1.0)

fig.gca().axis([-125, -65, 25, 50])
fig.gca().axis('off')
fig.savefig("states.png", facecolor='#F2F2F2', edgecolor='#F2F2F2')
Exemple #59
0
            # if closest existing SFR segment is first-order (no upsegs), route to next downstream segment
            # this helps avoid problems of artificially routing water to first order streams that are dry
            if existing_SFR_df.iloc[closest]['upseg'] == 0:
                outseg = existing_SFR_df.iloc[closest]['outseg']
            else:
                outseg = existing_SFR_df.iloc[closest]['segment']
            new_streamcells_df.Outseg[new_streamcells_df['Segment'] == seg] = outseg
            # set minimum elevation for segment from existing SFR
            out_elevation = existing_SFR_df.iloc[closest][existing_sfr_elevation_attribute]
            new_streamcells_df.Elevmin[new_streamcells_df['Segment'] == seg] = out_elevation

    # or, test for proximity to grid boundary (outlet condition)
    else:
        # make a buffer of max_distance_to_model_boundary around segment endpoint
        endpoint = Point(data.iloc[-1]['X_end'], data.iloc[-1]['Y_end'])
        endpoint_buff = endpoint.buffer(max_distance_to_model_boundary)

        # test for intersection with active domain bound
        if endpoint_buff.intersects(MFbound):
            new_streamcells_df.Outseg[new_streamcells_df['Segment'] == seg] = 0
            new_streamcells_df.Elevmin[new_streamcells_df['Segment'] == seg] = 0
        else:
            continue

# for now, leave in unrouted segments
'''
# add FragID field identifying unique river_explode segments if one doesn't exist
arcpy.MakeFeatureLayer_management(stream_fragments, "river_explode")
Fields = [f.name.lower() for f in arcpy.ListFields("river_explode")]
if "fragid" not in Fields:
    arcpy.AddField_management(stream_fragments, "FragID", "LONG")