def test_calculate_angle():
    a = Point(0, 0)
    b = Point(1, 1)
    c = Point(2, 0)

    angle = calculate_angle(a, b, c)
    assert np.isclose(angle, 90.0)
Ejemplo n.º 2
0
def circle_sensor(SensorName, Sensor_coord, r=1):
    """
    SensorName : nom du(des) sensor(s) souhaité(s), Sensor_coord : résultat de la fonction reading_gps_file
    r : rayon en metre, 1.00 m par défaut
    Output : 
    list_coord_circle = list des coordonnes des extremites de chaque cercle
    Shape_to_json     = list Proprietes geometriques de chaque cercle
    circle_name       = list de noms des sensors
    
    """
    list_coord_circle = []
    Shape_to_json = []
    circle_name = []

    for SensorName in SensorName:
        sensor_GPS = Sensor_coord.loc[Sensor_coord['SensorName'] == str(
            SensorName)]
        center = Point(sensor_GPS["x"], sensor_GPS["y"])  # point central
        circle = center.buffer(r)
        x_circle, y_circle = circle.exterior.xy  #Val de chaque extremitees du cercle
        list_coord_circle.append([np.array(x_circle), np.array(y_circle)])

        # Transfo des donnees en Geoseries :
        #Json -> https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
        # Format qui contient toutes les proprietes + points ext du cercle
        Shape_to_json.append(gpd.GeoSeries([circle]).to_json())
        circle_name.append(sensor_GPS['SensorName'])

    return list_coord_circle, Shape_to_json, circle_name
Ejemplo n.º 3
0
 def test_get_intersects_select_nearest(self):
     pt = Point(-99, 39)
     return_indices = [True, False]
     use_spatial_index = [True, False]
     select_nearest = [True, False]
     abstraction = ['polygon', 'point']
     bounds = [True, False]
     for args in itertools.product(return_indices, use_spatial_index, select_nearest, abstraction, bounds):
         ri, usi, sn, a, b = args
         sdim = self.get_sdim(bounds=b)
         sdim.abstraction = a
         ret = sdim.get_intersects(pt.buffer(1), select_nearest=sn, return_indices=ri)
         ## return_indice will return a tuple if True
         if ri:
             ret, ret_slc = ret
         if sn:
             ## select_nearest=True always returns a single element
             self.assertEqual(ret.shape, (1, 1))
             try:
                 self.assertTrue(ret.geom.polygon.value[0,0].centroid.almost_equals(pt))
             ## polygons will not be present if the abstraction is point or there are no bounds on the created
             ## spatial dimension object
             except ImproperPolygonBoundsError:
                 if a == 'point' or b is False:
                     self.assertTrue(ret.geom.point.value[0, 0].almost_equals(pt))
                 else:
                     raise
         ## if we are not returning the nearest geometry...
         else:
             ## bounds with a spatial abstraction of polygon will have this dimension
             if b and a == 'polygon':
                 self.assertEqual(ret.shape, (3, 3))
             ## with points, there is only intersecting geometry
             else:
                 self.assertEqual(ret.shape, (1, 1))
Ejemplo n.º 4
0
def calc_distance_and_angle(p: LocationLocal, ref_p: LocationLocal, rel_angle=0):
        # if type(p) is LocationGlobal or LocationGlobalRelative:
        #         p = latlon_to_xy()

        p = Point(p.east, p.north) 
        ref_p = Point(ref_p.east, ref_p.north)
        # transform to local coordinates
        p_local = affine_transform(p, [1,0,0,1, -ref_p.x, -ref_p.y])
        # alpha = -90 # plus 90 so north is a heading of 0 degrees.With shapely positive rotations are counter clockwise 
        # p_local = rotate(p_local, alpha, origin=(0,0)) # take into account the relative angle of the plane
        # # convert to polar coordinates
        # distance = math.sqrt(pow(p.x - ref_p.x, 2) + pow(p.y - ref_p.y, 2))
        # angle = math.atan((p.x - ref_p.x) / (p.y - ref_p.y))
        (distance, angle) = cmath.polar(complex(p_local.x, p_local.y)) # angle is in radians
        
        # convert to degrees and change axis
        # +90 to set north to heading 0
        angle = 90 - math.degrees(angle) - rel_angle

        # only positive angles
        if angle < 0:
            angle+=360

        # only angles under 360
        if angle > 360:
            angle-=360

        return (distance, angle)
Ejemplo n.º 5
0
    def match_shapes(self, shapes, buffer=0.01):
        """
        checks if shapes are completely within each others buffers, aggregates routes for these
        :return:
        """
        # buffer for spatial self join
        first_points = shapes["geometry"].apply(lambda x: Point(x.coords[0]))
        last_points = shapes["geometry"].apply(lambda x: Point(x.coords[-1]))

        points = pd.concat([first_points, last_points])
        point_df = points.to_frame(name='geometry')
        #point_df = point_df.set_geometry(point_df["geometry"], crs=self.crs_eurefin)
        point_df = point_df.set_geometry(point_df["geometry"],
                                         crs=self.crs_wgs)

        #buffer = point_df.buffer(30)
        #buffer = GeoDataFrame(crs=self.crs_eurefin, geometry=point_df.buffer(buffer))
        buffer = GeoDataFrame(crs=self.crs_wgs,
                              geometry=point_df.buffer(buffer))

        buffer["everything"] = 1
        gdf_poly = buffer.dissolve(by="everything")
        polygons = None
        for geoms in gdf_poly["geometry"]:
            polygons = [polygon for polygon in geoms]

        #single_parts = GeoDataFrame(crs=self.crs_eurefin, geometry=polygons)
        single_parts = GeoDataFrame(crs=self.crs_wgs, geometry=polygons)

        single_parts['new_stop_I'] = single_parts.index

        gdf_joined = sjoin(shapes, single_parts, how="left", op='within')
        return gdf_joined
Ejemplo n.º 6
0
def contains(x1, y1, x2, y2, radius, origin1=WGS84, origin2=WGS84, destination=PA_SP_SOUTH):
    '''
    :param x: x coordinate or longitude
    :param y: y coordiante or latitude
    :param radius: radius in miles
    :param projection:
    :return:
    '''
    # project input x1,y1 to PA state plane
    try:
        x, y = pyproj.transform(pyproj.Proj(origin1),
                                pyproj.Proj(destination, preserve_units=True),
                                x1, y1)
        # get circle from first input
        p = Point(x, y)
        circle = p.buffer(radius * MILES)

        # project x2, y2 to same plane
        x, y = pyproj.transform(pyproj.Proj(origin2),
                                pyproj.Proj(destination, preserve_units=True),
                                x2, y2)
        p = Point(x, y)
        return circle.contains(p)
    except:
        return False
Ejemplo n.º 7
0
def IsArcStrictIntersectPoly(arc, poly):
    # First check if two points in it is in poly.
    # Touching is OK.
    if poly.contains(Point(*arc.AngleToPoint(arc.MidAngle()))):
        return True

    # Then, check if arc intersect any of the poly's boundaries.
    intersections = CirclePolygonIntersections(arc, poly)

    # Now, classify the intersections that belongs to the arcs (including boundaries)
    angles = []
    for intersection in intersections:
        if arc.IsPointOnArcOrOnArcBoundary(intersection):
            angles.append(arc.PointToAngle(intersection))

    angles.append(arc._begin_radian)
    angles.append(arc._end_radian)

    angles.sort(
        key=lambda angle: (angle - arc._begin_radian) % (math.pi * 2.0))

    for p1, p2 in zip(angles, angles[1:]):
        if abs(p1 - p2) <= EPS:
            continue
        dist = (p2 - p1) % (math.pi * 2.0)
        midangle = (p1 + dist / 2.0) % (math.pi * 2.0)
        point = arc.AngleToPoint(midangle)
        if poly.contains(Point(point[0], point[1])):
            return True

    return False
Ejemplo n.º 8
0
def gen_poly3(x1, x2, x3, y1, y2, y3):  # roundabout
    poly1 = Polygon(
        ((0, 0), (0, (y1 + y2 + y3) / 2 - y2), ((x1 + x2 + x3) / 2 - y2 * 3,
                                                (y1 + y2 + y3) / 2 - y2),
         ((x1 + x2 + x3) / 2 - x2,
          (y1 + y2 + y3) / 2 - y2 * 3), ((x1 + x2 + x3) / 2 - x2, 0)))
    poly2 = Polygon(((0, (y1 + y2 + y3) / 2 + y2), (0, y1 + y2 + y3),
                     ((x1 + x2 + x3) / 2 - x2, y1 + y2 + y3),
                     ((x1 + x2 + x3) / 2 - x2, (y1 + y2 + y3) / 2 + y2 * 3),
                     ((x1 + x2 + x3) / 2 - y2 * 3, (y1 + y2 + y3) / 2 + y2)))
    poly3 = Polygon(
        (((x1 + x2 + x3) / 2 + x2, 0), ((x1 + x2 + x3) / 2 + x2,
                                        (y1 + y2 + y3) / 2 - y2 * 3),
         ((x1 + x2 + x3) / 2 + y2 * 3, (y1 + y2 + y3) / 2 - y2),
         (x1 + x2 + x3, (y1 + y2 + y3) / 2 - y2), (x1 + x2 + x3, 0)))
    poly4 = Polygon(
        (((x1 + x2 + x3) / 2 + y2 * 3, (y1 + y2 + y3) / 2 + y2),
         ((x1 + x2 + x3) / 2 + x2, (y1 + y2 + y3) / 2 + y2 * 3),
         ((x1 + x2 + x3) / 2 + x2, y1 + y2 + y3), (x1 + x2 + x3, y1 + y2 + y3),
         (x1 + x2 + x3, (y1 + y2 + y3) / 2 + y2)))
    p = Point((x1 + x2 + x3) / 2, (y1 + y2 + y3) / 2)
    circle = p.buffer(y2)
    polyc = list(circle.exterior.coords)
    poly5 = Polygon(polyc)
    polys = [poly1, poly2, poly3, poly4, poly5]
    return gp.GeoDataFrame(geometry=polys)
Ejemplo n.º 9
0
    def intersects(self, polygon):
        ## do the initial grid subset
        grid = self.grid.subset(polygon=polygon)
        ## a prepared polygon
        prep_polygon = prepared.prep(polygon)
        ## the fill arrays
        geom = np.ones(grid.shape, dtype=object)
        geom = np.ma.array(geom, mask=True)
        geom_mask = geom.mask

        try:
            row = grid.row.value
            col = grid.column.value
            for ii, jj in product(range(row.shape[0]), range(col.shape[0])):
                pt = Point(col[jj], row[ii])
                geom[ii, jj] = pt
                if prep_polygon.intersects(pt):
                    geom_mask[ii, jj] = False
                else:
                    geom_mask[ii, jj] = True
        ## NcGridMatrixDimension correction
        except AttributeError:
            _row = grid.row
            _col = grid.column
            for ii, jj in iter_array(_row):
                pt = Point(_col[ii, jj], _row[ii, jj])
                geom[ii, jj] = pt
                if prep_polygon.intersects(pt):
                    geom_mask[ii, jj] = False
                else:
                    geom_mask[ii, jj] = True

        ret = self.__class__(grid=grid, geom=geom, uid=grid.uid)

        return (ret)
def draw_xg_circle (fig, ax, distance_x,distance_y,radius,color, e_color):
    p = Point(distance_x,distance_y)
    circle = p.buffer(radius)
    x,y = circle.exterior.xy
    x = np.array(x) / 1.05
    y = np.array(y) / 0.6
    ax.fill(x, y, alpha=0.5, fc=color, ec=e_color)
    return
Ejemplo n.º 11
0
 def _choose_lilly_pad_position(self, pad_radius):
     min_x, min_y, max_x, max_y = self.pond.circle.get_bounds()
     while True:
         x = random.uniform(min_x, max_x)
         y = random.uniform(min_y, max_y)
         pad = Circle(Point(x, y), pad_radius)
         if self.pond.lilly_pad_in_pond(pad) and not self._is_overlapping_current_lilly_pads(pad):
             return Point(x, y)
Ejemplo n.º 12
0
def flowbandwidth(flowline1, flowline2, offsets):
    widths = np.empty(0)
    for i, pt in enumerate(flowline1.x):
        widths = np.append(
            widths,
            Point(flowline1.x[i], flowline1.y[i]).distance(
                Point(flowline2.x[i], flowline2.y[i])))
    return widths
Ejemplo n.º 13
0
def iou(params0, params1):
    row0, col0, rad0 = params0
    row1, col1, rad1 = params1

    shape0 = Point(row0, col0).buffer(rad0)
    shape1 = Point(row1, col1).buffer(rad1)

    return (shape0.intersection(shape1).area / shape0.union(shape1).area)
Ejemplo n.º 14
0
def create_base_stations_points(centers, radius):
    Bx = []
    for center in centers:
        point = Point(center[0], center[1])
        circle = point.buffer(radius)
        Bx.append(circle)

    return Bx
Ejemplo n.º 15
0
def calculate_fitness(worm, radius, city):

    circles = []
    for center in worm:
        point = Point(center[0], center[1])
        circles.append(point.buffer(radius))

    base_stations_polygon = cascaded_union(circles)
    intersection_area = base_stations_polygon.intersection(city).area
    return base_stations_polygon.intersection(city).area / city.area
Ejemplo n.º 16
0
 def test_move_to_lilly_pad_calls_lilly_pad_visit_method(self):
     # arrange
     mock_pad = mock.create_autospec(LillyPad)
     mock_pad.circle = Circle(Point(0, 0), 3)
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     # act
     frog._move_to_lilly_pad(mock_pad)
     # assert
     assert mock_pad.visit.called
Ejemplo n.º 17
0
 def test_move_to_lilly_pad_updates_frog_current_lilly_pad(self):
     # arrange
     mock_pad = mock.create_autospec(LillyPad)
     mock_pad.circle = Circle(Point(0, 0), 3)
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     # act
     frog._move_to_lilly_pad(mock_pad)
     # assert
     assert frog.current_lilly_pad == mock_pad
Ejemplo n.º 18
0
 def test_find_possible_pads_returns_no_pads_if_nearby_pad_occupied(self):
     # arrange
     position = Point(2, 2)
     frog = Frog(position, 5, 0)
     pad = LillyPad(Point(2, 4), 1)
     pad.currently_occupied = True
     # act
     possible_pads = frog._find_possible_lilly_pads([pad])
     # assert
     assert len(possible_pads) == 0
Ejemplo n.º 19
0
 def test_find_possible_lilly_pads_returns_empty_list_when_none_are_available(
         self):
     # arrange
     position = Point(20, 20)
     frog = Frog(position, 1, 0)
     pad = LillyPad(Point(2, 4), 1)
     # act
     possible_pads = frog._find_possible_lilly_pads([pad])
     # assert
     assert len(possible_pads) == 0
Ejemplo n.º 20
0
 def test_find_possible_lilly_pads_returns_list_of_lilly_pads_when_some_are_available(
         self):
     # arrange
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     pad = LillyPad(Point(2, 4), 1)
     # act
     possible_pads = frog._find_possible_lilly_pads([pad])
     # assert
     assert pad in possible_pads
Ejemplo n.º 21
0
 def get_egocentric_spatial_relation_pivot(self, ref_point: Point,
                                           route: GeoDataFrame) -> str:
     line = LineString(route['geometry'].tolist())
     dist_projected = line.project(ref_point)
     cut_geometry = util.cut(line, dist_projected)
     first_segment = cut_geometry[0]
     coords = list(first_segment.coords)
     return self.calc_spatial_relation_for_line(ref_point,
                                                Point(coords[-1]),
                                                Point(coords[-2]))
Ejemplo n.º 22
0
    def geo_valid(self, json_input):
        """
        In order to make a guess at MoT we have to have OSM data. geoms is a list of geometries (closed polygons)
        that define the regions of validity of this model. This function returns a list of visit id's that are valid
        TODO: If we don't specify a lat and lon, go look this up.
        :param visits: A list of dictionaries containing a lat, a lon and a visit id
        :param CONFIG: The parsed config file
        :return: Will output a list of visits that are within the regions of validity
        """

        # geoms = read_geo_valid(CONFIG)
        p = pd.DataFrame(json_input)

        p = p[p['mot'] == 'train']
        if p.empty:
            logging.debug('No train journey within json')
            return [], []

        # Is within region of geovalidity
        is_within = p.apply(lambda x: np.all([
            geom.contains(Point(x['start_lon'], x['start_lat'])) and geom.
            contains(Point(x['end_lon'], x['end_lat'])) for geom in self.geoms
        ]),
                            axis=1).values
        # is greater than the min distance
        is_gt_min_dist = p.apply(lambda x: vincenty(
            (x['start_lat'], x['start_lon']),
            (x['end_lat'], x['end_lon'])).meters > CONFIG.getint(
                'geovalidity', 'MIN_DIST_BTW_PTS'),
                                 axis=1).values
        # If trips need to be discarded, log in in the failed trips table
        if any(~is_within) or any(~is_gt_min_dist):
            p['failure_cause'] = ''
            p['datetime_created'] = datetime.utcnow()

            error_msg = 'Not within region of geo-validity ({}). '
            p.loc[~is_within, 'failure_cause'] += error_msg.format(
                CONFIG.get('geovalidity', 'VALID_REGION_WKT'))

            error_msg = 'Start and end point of MoT segment too close (within {} meters of each-other). '
            p.loc[~is_gt_min_dist, 'failure_cause'] += error_msg.format(
                CONFIG.getint('geovalidity', 'MIN_DIST_BTW_PTS'))

            col_list = [
                'mot_segment_id', 'failure_cause', 'datetime_created',
                'bound_from_id', 'bound_to_id'
            ]
            failed_trips = p.loc[p['failure_cause'] != '', col_list]
            update_postgres(failed_trips, 'train_trips_failed', DB)

        mask = np.logical_and(is_within, is_gt_min_dist)
        loc_bounds = p.loc[mask,
                           ['mot_segment_id', 'bound_from_id', 'bound_to_id']]
        return p.loc[mask, 'mot_segment_id'].tolist(), loc_bounds
Ejemplo n.º 23
0
    def test_create_line_from_points(self):
        geo_point_1 = Point(0.0, 0.0)
        geo_point_2 = Point(1.0, 1.0)
        expected_line = LineString([
            [0.0, 0.0],
            [1.0, 1.0],
        ])

        geo_line = geo_fields.GeoLine.from_points(self.env.cr, geo_point_1,
                                                  geo_point_2)
        self.assertEqual(geo_line, expected_line)
Ejemplo n.º 24
0
def is_square(test_geom):
    if isinstance(test_geom, Polygon):
        if len(test_geom.exterior.coords) is 5:
            x_pts, y_pts = test_geom.exterior.coords.xy
            perimeter = zip(x_pts, y_pts)
            len_sides = []
            for i in range(len(perimeter)):
                len_sides.append(Point(perimeter[i]).distance(Point(perimeter[i-1])))
            len_sides.remove(0.0)
            if len(set(len_sides)) <= 1:
                #print(">>> SQUARE: "+ str(perimeter)+ " | SIDES: " + str(len_sides))
                return True
Ejemplo n.º 25
0
 def test_move_to_lilly_pad_calls_leave_on_current_lilly_pad(self):
     # arrange
     mock_current_pad = mock.create_autospec(LillyPad)
     mock_dest_pad = mock.create_autospec(LillyPad)
     mock_dest_pad.circle = Circle(Point(0, 0), 3)
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     frog.current_lilly_pad = mock_current_pad
     # act
     frog._move_to_lilly_pad(mock_dest_pad)
     # assert
     assert mock_current_pad.leave.called
Ejemplo n.º 26
0
    def find_stations_in_geometry(shape,
                                  contour_dist=0,
                                  start_date=None,
                                  end_date=None):
        stations = Station.get_stations(start_date, end_date)

        # For performance purposes, find a cutoff distance beyond which stations are ignored
        center = shape.centroid
        hull_points = [
            Point(x, y) for x, y in zip(*shape.convex_hull.exterior.xy)
        ]
        furthest_point = max(hull_points, key=lambda x: center.distance(x))
        max_dist = Station.distance(center.y, center.x, furthest_point.y,
                                    furthest_point.x)
        max_dist += contour_dist

        # Evaluate the distance with all stations
        shapes = shape if shape.geom_type == 'MultiPolygon' else [shape]
        distances = []
        for station in stations:
            # First get an approximate distance from the centroid
            distance_approx = station.distance_from(center.y, center.x)
            if distance_approx > max_dist:
                distances.append(None)
                continue

            # Points inside the borders have a distance of 0
            station_point = Point(station.longitude, station.latitude)
            if any(sub_shape.contains(station_point) for sub_shape in shapes):
                distances.append(0)
                continue

            # Otherwise, evaluate the real distance from the region borders
            distance = 99999
            for sub_shape in shapes:
                exterior = sub_shape.exterior
                projection = exterior.interpolate(
                    exterior.project(station_point))
                distance = min(
                    distance, station.distance_from(projection.y,
                                                    projection.x))
            distances.append(distance if distance < contour_dist else None)
        distances = np.array(distances)

        # Sort stations based on their distance
        closest = [(station, distance)
                   for station, distance in zip(stations, distances)
                   if distance is not None]
        closest.sort(key=lambda x: x[1])

        # Return the sorted stations and distances
        return closest
Ejemplo n.º 27
0
    def test_selecting_single_value(self):
        rd = self.test_data.get_rd('cancm4_tas')
        lat_index = 32
        lon_index = 97
        with nc_scope(rd.uri) as ds:
            lat_value = ds.variables['lat'][lat_index]
            lon_value = ds.variables['lon'][lon_index]
            data_values = ds.variables['tas'][:, lat_index, lon_index]

        ops = ocgis.OcgOperations(dataset=rd, geom=[lon_value, lat_value])
        ret = ops.execute()
        actual = ret.get_element(variable_name='tas').get_masked_value()
        values = np.squeeze(actual)
        self.assertNumpyAll(data_values, values.data)
        self.assertFalse(np.any(values.mask))

        geom = Point(lon_value, lat_value).buffer(0.001)
        ops = ocgis.OcgOperations(dataset=rd, geom=geom)
        ret = ops.execute()
        actual = ret.get_element(variable_name='tas').get_masked_value()
        values = np.squeeze(actual)
        self.assertNumpyAll(data_values, values.data)
        self.assertFalse(np.any(values.mask))

        geom = Point(lon_value - 360., lat_value).buffer(0.001)
        ops = ocgis.OcgOperations(dataset=rd, geom=geom)
        ret = ops.execute()
        actual = ret.get_element(variable_name='tas').get_masked_value()
        values = np.squeeze(actual)
        self.assertNumpyAll(data_values, values.data)
        self.assertFalse(np.any(values.mask))

        geom = Point(lon_value - 360., lat_value).buffer(0.001)
        ops = ocgis.OcgOperations(dataset=rd,
                                  geom=geom,
                                  aggregate=True,
                                  spatial_operation='clip')
        ret = ops.execute()
        actual = ret.get_element(variable_name='tas').get_masked_value()
        values = np.squeeze(actual)
        self.assertNumpyAll(data_values, values.data)
        self.assertFalse(np.any(values.mask))

        ops = ocgis.OcgOperations(dataset=rd,
                                  geom=[lon_value, lat_value],
                                  search_radius_mult=0.1,
                                  output_format='nc')
        ret = ops.execute()
        with nc_scope(ret) as ds:
            values = np.squeeze(ds.variables['tas'][:])
            self.assertNumpyAll(data_values, values)
def test_halve_line(line):
    """There should be
    - two lines returned
    - they should be of equal length
    - The last point in the first half should match the first point in the second half
    - The midpoint should intersect the original line
    """
    halves = split_line(line)

    assert len(halves) == 2
    assert np.allclose(halves[0].length, halves[1].length)

    midpoint = Point(halves[0].coords[-1])
    assert midpoint == Point(halves[1].coords[0])
    assert midpoint.buffer(.00000001).intersects(line)
Ejemplo n.º 29
0
    def get_bbox_from_url(wms_url):
        """
        Parses wms url for BBOX parameter an returns these points as suitable values for ViewServiceRecord.
        Args:
            wms_url (str): wms url which includes a BBOX parameter to parse.

        Returns:
            set of two shapely.geometry.point.Point: min and max coordinates of bounding box.
        """
        _, params = parse_url(wms_url)
        bbox = params.get('BBOX')
        if bbox is None or len(bbox[0].split(',')) != 4:
            return None, None
        points = bbox[0].split(',')
        return Point(float(points[0]), float(points[1])), Point(float(points[2]), float(points[3]))
Ejemplo n.º 30
0
def get_linestring_distance(line: LineString) -> int:
  '''Calculate the line length in meters.
  Arguments:
    route: The line that length calculation will be performed on.
  Returns:
    Line length in meters.
  '''
  dist = 0
  point_1 =  Point(line.coords[0])
  for coord in line.coords[1:]:
    point_2 = Point(coord)
    dist += get_distance_between_points(point_1, point_2)
    point_1 = point_2

  return dist
Ejemplo n.º 31
0
def get_line_length(line: LineString) -> float:
  '''Calculate the length of a line in meters.
  Arguments:
    line: The line to calculate its length.
  Returns:
    The length of the line in meters
  '''
  dist = 0
  point_1 = Point(line.coords[0])
  for coord in line.coords[1:]:
    point_2 = Point(coord)
    dist += get_distance_between_points(point_1, point_2)
    point_1 = point_2

  return dist
Ejemplo n.º 32
0
 def __init__(self, coords, groups, velocity, angle):
     super().__init__(*groups)
     self.image = load_image('enemy_bullet.png')
     self.image = pygame.transform.scale(self.image, (4, 4))
     self.rect = self.image.get_rect().move(*coords)
     self.velocity, self.angle = velocity, angle
     self.hitbox = Point(coords[0] + 2, coords[1] + 2).buffer(2.0)
Ejemplo n.º 33
0
def CircleLineSegmentIntersections(circle, segment):
  center = Point(circle.center[0], circle.center[1])
  distance = segment.distance(center)
  if distance > circle.radius + EPS:
    return []

  super_point = ShortestToLine(segment, circle.center)
  super_point_p = Point(super_point[0], super_point[1])

  orig_point = segment.coords[0]
  dest_point = segment.coords[1]

  dist = Point(orig_point[0], orig_point[1]).distance(super_point_p)
  if ((dest_point[0] - orig_point[0]) * (orig_point[0] - super_point[0]) >= 0 and
      (dest_point[1] - orig_point[1]) * (orig_point[1] - super_point[1]) >= 0):
    dist *= -1

  distance = center.distance(super_point_p)
  if distance > circle.radius + EPS:
    return []

  val = circle.radius**2 - distance**2
  if val < 0:
    val = 0
  front_side = math.sqrt(val)
  intersections = []
  for i in range(-1, 2, 2):
    if i == 1 and front_side < EPS:
      break

    new_dist = dist + front_side * i
    if new_dist < -EPS or new_dist > segment.length + EPS:
      continue
    intersection_point = segment.interpolate(new_dist)
    intersections.append([intersection_point.x, intersection_point.y])
  return intersections
Ejemplo n.º 34
0
def main():

    spatialReference = osr.SpatialReference()
    spatialReference.ImportFromProj4('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')


    driver = ogr.GetDriverByName("ESRI Shapefile")

    shp_dir = "praries_basins"
    shutil.rmtree(shp_dir)
    shapeData = driver.CreateDataSource(shp_dir)



    layer = shapeData.CreateLayer('layer1', spatialReference, ogr.wkbPolygon)
    #assert isinstance(layer, Layer)
    layer.CreateField(ogr.FieldDefn("BasinId"))
    layerDefinition = layer.GetLayerDefn()


    input_path = "data/praries_basins/Boundaries_lat_lon.txt"

    lines = open(input_path).readlines()


    lons2d = polar_stereographic.lons
    lats2d = polar_stereographic.lats

    id_to_points = {}
    anomaly_i = 1
    point_prev = None
    for line in lines:
        if line.strip() == "": continue
        fields = line.split()
        the_id = fields[0]
        lon = float(fields[1])
        lat = float(fields[2])

        if the_id not in id_to_points:
            id_to_points[the_id] = []

        if int(the_id) >= 16:
            the_point = Point(lon, lat)
            if point_prev is not None:
                the_dist = the_point.distance(point_prev)
                if the_dist > 0.5:
                    id_to_points[the_id + "_{0}".format(anomaly_i)] = id_to_points[the_id]
                    id_to_points[the_id] = []
                    anomaly_i += 1
            point_prev = the_point

        id_to_points[the_id].append((lon, lat))
        pass

    polygons = []
    featureIndex = 0
    for the_id, points in id_to_points.items():

        if not len(points): continue

        feature = ogr.Feature(layerDefinition)

        feature.SetField("BasinId", the_id)

        #create a polygon using shapely
        p = Polygon(shell=points)
        #print p.wkt
        polygons.append(p)
        pGdal = ogr.CreateGeometryFromWkb(p.wkb)
        feature.SetGeometry(pGdal)
        feature.SetFID(featureIndex)
        layer.CreateFeature(feature)
        featureIndex += 1

    shapeData.Destroy()




    pass
Ejemplo n.º 35
0
 def simple_polygon(self):
     pt = Point(200,0.0)
     return(pt.buffer(8,1))
Ejemplo n.º 36
0
def get_mesh2_variables(features):
    """
    :param features: A features sequence as returned from :func:`ugrid.helpers.get_features_from_shapefile`.
    :type features: :class:`collections.deque`
    :returns: A tuple of arrays with index locations corresponding to:

    ===== ================ =============================
    Index Name             Type
    ===== ================ =============================
    0     Mesh2_face_nodes :class:`numpy.ma.MaskedArray`
    1     Mesh2_face_edges :class:`numpy.ma.MaskedArray`
    2     Mesh2_edge_nodes :class:`numpy.ndarray`
    3     Mesh2_node_x     :class:`numpy.ndarray`
    4     Mesh2_node_y     :class:`numpy.ndarray`
    5     Mesh2_face_links :class:`numpy.ndarray`
    ===== ================ =============================

    Information on individual variables may be found here: https://github.com/ugrid-conventions/ugrid-conventions/blob/9b6540405b940f0a9299af9dfb5e7c04b5074bf7/ugrid-conventions.md#2d-flexible-mesh-mixed-triangles-quadrilaterals-etc-topology

    :rtype: tuple (see table for array types)
    """

    # construct the links between faces (e.g. neighbors)
    Mesh2_face_links = deque()
    for idx_source in range(len(features)):
        ref_object = features[idx_source]['geometry']['object']
        for idx_target in range(len(features)):
            # skip if it is checking against itself
            if idx_source == idx_target:
                continue
            else:
                # if the objects only touch they are neighbors and share nodes
                if ref_object.touches(features[idx_target]['geometry']['object']):
                    Mesh2_face_links.append([features[idx_source]['fid'], features[idx_target]['fid']])
                else:
                    continue
    # convert to numpy array for faster comparisons
    Mesh2_face_links = np.array(Mesh2_face_links, dtype=np.int32)

    # the number of faces
    nMesh2_face = len(features)
    # for polygon geometries the first coordinate is repeated at the end of the sequence.
    nMaxMesh2_face_nodes = max([len(feature['geometry']['coordinates'][0]) - 1 for feature in features])
    Mesh2_face_nodes = np.ma.array(np.zeros((nMesh2_face, nMaxMesh2_face_nodes), dtype=np.int32), mask=True)
    # the edge mapping has the same shape as the node mapping
    Mesh2_face_edges = np.zeros_like(Mesh2_face_nodes)

    # holds the start and nodes for each edge
    Mesh2_edge_nodes = deque()
    # holds the raw coordinates of the nodes
    Mesh2_node_x = deque()
    Mesh2_node_y = deque()

    # flag to indicate if this is the first face encountered
    first = True
    # global point index counter
    idx_point = 0
    # global edge index counter
    idx_edge = 0
    # holds point geometry objects
    points_obj = deque()
    # loop through each polygon
    for feature in features:
        # reference the face index
        fid = feature['fid']
        # just load everything if this is the first polygon
        if first:
            # store the point values. remember to ignore the last coordinate.
            for ii in range(len(feature['geometry']['coordinates'][0]) - 1):
                coords = feature['geometry']['coordinates'][0][ii]
                # create and store the point geometry object
                points_obj.append(Point(coords[0], coords[1]))
                # store the x and y coordinates
                Mesh2_node_x.append(coords[0])
                Mesh2_node_y.append(coords[1])
                # increment the point index
                idx_point += 1
            # map the node indices for the face
            Mesh2_face_nodes[fid, 0:idx_point] = range(0, idx_point)
            # construct the edges. compress the node slice to remove any masked values at the tail.
            for start_node_idx, end_node_idx in iter_edge_nodes(Mesh2_face_nodes[fid, :].compressed()):
                Mesh2_edge_nodes.append((start_node_idx, end_node_idx))
                idx_edge += 1
            # map the edges to faces
            Mesh2_face_edges[fid, 0:idx_edge] = range(0, idx_edge)
            # switch the loop flag to indicate the first face has been dealt with
            first = False
        else:
            # holds new node coordinates for the face
            new_Mesh2_face_nodes = deque()
            # only search neighboring faces
            neighbor_face_indices = Mesh2_face_links[Mesh2_face_links[:, 0] == fid, 1]
            for ii in range(len(feature['geometry']['coordinates'][0]) - 1):
                # logic flag to indicate if the point has been found
                found = False
                coords = feature['geometry']['coordinates'][0][ii]
                pt = Point(coords[0], coords[1])
                # search the neighboring faces for matching nodes
                for neighbor_face_index in neighbor_face_indices.flat:
                    # break out of loop if the point has been found
                    if found:
                        break
                    # search over the neighboring face's nodes
                    for neighbor_face_node_index in Mesh2_face_nodes[neighbor_face_index, :].compressed():
                        if pt.almost_equals(points_obj[neighbor_face_node_index]):
                            new_Mesh2_face_nodes.append(neighbor_face_node_index)
                            # point is found, no need to continue with loop
                            found = True
                            break
                # add the new node if it has not been found
                if not found:
                    # add the point object to the collection
                    points_obj.append(pt)
                    # add the coordinates of the new point
                    Mesh2_node_x.append(coords[0])
                    Mesh2_node_y.append(coords[1])
                    # append the index of this new point
                    new_Mesh2_face_nodes.append(idx_point)
                    # increment the point index
                    idx_point += 1
            # map the node indices for the face
            Mesh2_face_nodes[fid, 0:len(new_Mesh2_face_nodes)] = new_Mesh2_face_nodes
            # find and map the edges
            new_Mesh2_face_edges = deque()
            for start_node_idx, end_node_idx in iter_edge_nodes(Mesh2_face_nodes[fid, :].compressed()):
                # flag to indicate if edge has been found
                found_edge = False
                # search existing edge-node combinations accounting for ordering
                for idx_edge_nodes, edge_nodes in enumerate(Mesh2_edge_nodes):
                    # swap the node ordering
                    if edge_nodes == (start_node_idx, end_node_idx) or edge_nodes == (end_node_idx, start_node_idx):
                        new_Mesh2_face_edges.append(idx_edge_nodes)
                        found_edge = True
                        break
                if not found_edge:
                    Mesh2_edge_nodes.append((start_node_idx, end_node_idx))
                    new_Mesh2_face_edges.append(idx_edge)
                    idx_edge += 1
            # update the face-edge mapping
            Mesh2_face_edges[fid, 0:len(new_Mesh2_face_edges)] = new_Mesh2_face_edges

    return Mesh2_face_nodes, \
           Mesh2_face_edges, \
           np.array(Mesh2_edge_nodes, dtype=np.int32), \
           np.array(Mesh2_node_x, dtype=np.float32), \
           np.array(Mesh2_node_y, dtype=np.float32), \
           np.array(Mesh2_face_links, dtype=np.int32)
Ejemplo n.º 37
0
    fpath = args.lasfile
    opath = "%s/%s" % (args.outdir.rstrip('/'),args.lasfile.split('/')[-1])

    # prepare statistics
    points_read = 0
    points_kept = 0

    # open in- and output LAS-file
    f = lasfile.File(fpath,mode='r')
    o = lasfile.File(opath, header=f.header, mode='w')

    # extract points
    #print "processing %s ..." % args.lasfile
    for point in f:
        points_read += 1
        p = Point(point.x, point.y)
        if p.within(wkt_poly) or p.intersects(wkt_poly):
            points_kept += 1
            o.write(point)

    # give feedback and remove empty output file
    o.close()
    f.close()
    if points_kept == 0:
        print "    no points found within WKT-poly"
        os.remove(opath)
    else:
        print "    created %s (kept %s of %s points)" % (opath,points_kept,points_read)

    # log times
    time_end = time.time()