Exemple #1
0
def filter_building(way, b, polygons):
    near_way_points = nearest_points(polygons[b['id']], way)
    b_near_way = near_way_points[0]
    buff = b_near_way.buffer(b_near_way.distance(near_way_points[1]) + 0.00001,
                             mitre_limit=1.0)
    buff = shapely.affinity.scale(buff, 1.0, 0.75)

    n_intersect = buff.boundary.intersection(way)
    n_intersect = [n_intersect] if isinstance(n_intersect,
                                              Point) else list(n_intersect)
    n_intersect = MultiPoint(n_intersect)

    filtered = True
    if n_intersect:
        nearest = nearest_points(polygons[b['id']], n_intersect)
        mp = MultiPoint(list(n_intersect) + [nearest[0]])

        try:
            mp = Polygon(mp)
            filtered = any(
                filter(
                    lambda (bid, p): bid != b['id'] and p.boundary.intersects(
                        mp.boundary), polygons.items()))
        except ValueError:
            pass

    return filtered
Exemple #2
0
def line_slice(startPt, stopPt, line):
    coords = list(line.coords)
    multi_line = MultiPoint(line.coords)

    if line.type == 'LineString':

        startVertex = nearest_points(multi_line,
                                     startPt['geometry'])[0].coords[0]
        stopVertex = nearest_points(multi_line,
                                    stopPt['geometry'])[0].coords[0]

        start_indx = coords.index(startVertex)
        stop_indx = coords.index(stopVertex)

        ends = []
        if start_indx <= stop_indx:
            ends = [start_indx, stop_indx]
        else:
            ends = [stop_indx, start_indx]

        clipCoords = coords[ends[0]:ends[1] + 1]

        if (len(clipCoords) == 1):
            clipCoords.append(clipCoords[0])

        return LineString(clipCoords)
Exemple #3
0
    def find_cut_distance(current_string: LineString, pair, frequency: int,
                          offset_distance: float, side: str):
        neighbor_string = LineString(
            [[pair.node_from.utm.north, pair.node_from.utm.east],
             [pair.node_to.utm.north, pair.node_to.utm.east]])
        offsetted_neighbor_string = neighbor_string.parallel_offset(
            frequency * offset_distance, side='left', resolution=10)

        # Project neighbor string onto current string.
        if side == 'back':
            projected_point = Point(
                nearest_points(
                    current_string,
                    Point(list(offsetted_neighbor_string.coords)[-1]))[0])
        else:
            projected_point = Point(
                nearest_points(
                    current_string,
                    Point(list(offsetted_neighbor_string.coords)[0]))[0])

        # Create a line from the side of the current string to the projected points.
        if side == 'back':
            line = LineString(
                [Point(list(current_string.coords)[0]), projected_point])
        else:
            line = LineString(
                [Point(list(current_string.coords)[-1]), projected_point])

        return line.length
def get_h_line(
    pts0: MultiPoint,
    pts1: MultiPoint,
) -> LineString:
    if isinstance(pts1, Point):
        pts1 = MultiPoint([pts1])
    if isinstance(pts0, Point):
        pts0 = MultiPoint([pts0])

    eps = 1e-6
    hdist = pts0.hausdorff_distance(pts1)
    ls = []

    for p0 in pts0:
        d = p0.distance(pts1)
        if abs(d - hdist) < eps:
            #return LineString(nearest_points(p0,pts1))
            ls.append(LineString(nearest_points(p0, pts1)))
    for p1 in pts1:
        d = p1.distance(pts0)
        if abs(d - hdist) < eps:
            #return LineString(nearest_points(p0,pts1))
            ls.append(LineString(nearest_points(p1, pts0)))

    return MultiLineString(ls)
Exemple #5
0
    def step(s, action):
        """Apply action, return new state, reward, done, empty info dict"""
        throttle, turn = action
        prev_dist = s.distance_to_centerline()
        s.move_car(throttle, turn)
        is_display_alive = s.draw()
        s.camera_view = s.display.read_screen()

        # increment measurements
        s.time += 1
        s.driving_dist += np.sqrt(s.car.dx**2+s.car.dy**2)
        cur_point = Point(s.car.x, s.car.y)
        if not hasattr(s, 'prev_track_point'):
            s.prev_track_point = nearest_points(s.track_center, Point(s.car.x, s.car.y))[0]
        cur_track_point = nearest_points(s.track_center, cur_point)[0]
        delta_track_dist = 0.0
        if s.is_on_track():
            angle = s.get_angle(cur_track_point.x, cur_track_point.y,
                                s.prev_track_point.x, s.prev_track_point.y)
            if (True):#angle > 0):
                delta_track_dist = cur_track_point.distance(s.prev_track_point)
                s.track_dist += delta_track_dist
        s.prev_track_point = cur_track_point

        # finalize other values
        #reward = delta_track_dist/s.car.max_v
        #reward = (abs(prev_dist) - abs(s.distance_to_centerline()))/70
        reward = 1.0 if s.is_on_track() else 0.0
        state = [s.camera_view.astype(np.float32)/255, np.array([s.time/100])] # true system includes camera, gyroscope,and accelerometer
        done = ((not is_display_alive) or (abs(s.distance_to_centerline()) > 80)) #implement your own logic on when to be done

        return state, reward, done, {}
    def step(s, action):
        """Apply action, return new state, reward, done, empty info dict"""
        s.throttle, s.steering_angle = action
        prev_dist = s.get_distance_to_center()
        s.move_car(s.throttle, s.steering_angle)
        is_display_alive = s.draw()
        s.camera_view = s.display.read_screen()

        # increment measurements
        s.time += 1
        s.driving_dist += np.sqrt(s.car.dx**2+s.car.dy**2)
        cur_point = Point(s.car.x, s.car.y)
        if not hasattr(s, 'prev_track_point'):
            s.prev_track_point = nearest_points(s.track_center, Point(s.car.x, s.car.y))[0]
        cur_track_point = nearest_points(s.track_center, cur_point)[0]
        delta_track_dist = 0.0
        if s.is_on_track():
            delta_track_dist = cur_track_point.distance(s.prev_track_point)
            s.track_dist += delta_track_dist
        s.prev_track_point = cur_track_point

        params = s.get_params()
        reward = s._reward_func(params)
        state = s.get_state()
        done = ((not is_display_alive) or (abs(s.get_distance_to_center()) > 80))

        return state, reward, done, {}
Exemple #7
0
    def moveBoundaryPoints(self):
        """ move boundary weights/points on the geometry boundary """

        self.timer.startTimer("moveBoundaryPoints")

        inner = Polygon(self.geometry[1])
        outer = Polygon(self.geometry[0])

        movement = np.zeros((np.shape(self.boundaryIdx)[0], 2))

        weightsBoundary = tf.Variable(tf.gather(self.weights,
                                                self.boundaryIdx),
                                      dtype=self.dataType).numpy()

        for idx in range(0, np.shape(self.boundaryIdx)[0]):

            point = Point(weightsBoundary[idx, 0], weightsBoundary[idx, 1])

            pOuter, p = nearest_points(outer.boundary, point)
            pInner, p = nearest_points(inner.boundary, point)

            if (point.distance(pInner) > point.distance(pOuter)):

                movement[idx, 0] = pOuter.x
                movement[idx, 1] = pOuter.y
            else:
                movement[idx, 0] = pInner.x
                movement[idx, 1] = pInner.y

        print(np.shape(self.boundaryIdx))
        print(np.shape(self.boundaryIdx))

        tf.compat.v1.scatter_update(self.weights, self.boundaryIdx, movement)

        self.timer.stopTimer("moveBoundaryPoints")
Exemple #8
0
def _extend_boundaries(baselines, bin_bl_map):
    # find baseline blob boundaries
    labelled = label(bin_bl_map)
    boundaries = []
    for x in regionprops(labelled):
        try:
            b = boundary_tracing(x)
            if len(b) > 3:
                boundaries.append(geom.Polygon(b).simplify(0.01).buffer(0))
        except Exception as e:
            logger.warning(f'Boundary tracing failed in baseline elongation: {e}')
            continue

    # extend lines to polygon boundary
    for bl in baselines:
        ls = geom.LineString(bl)
        try:
            boundary_pol = next(filter(lambda x: x.contains(ls), boundaries))
        except Exception:
            continue
        # 'left' side
        if boundary_pol.contains(geom.Point(bl[0])):
            l_point = boundary_pol.boundary.intersection(geom.LineString([(bl[0][0]-10*(bl[1][0]-bl[0][0]), bl[0][1]-10*(bl[1][1]-bl[0][1])), bl[0]]))
            if l_point.type != 'Point':
                bl[0] = np.array(nearest_points(geom.Point(bl[0]), boundary_pol)[1], 'int').tolist()
            else:
                bl[0] = np.array(l_point, 'int').tolist()
        # 'right' side
        if boundary_pol.contains(geom.Point(bl[-1])):
            r_point = boundary_pol.boundary.intersection(geom.LineString([(bl[-1][0]-10*(bl[-2][0]-bl[-1][0]), bl[-1][1]-10*(bl[-2][1]-bl[-1][1])), bl[-1]]))
            if r_point.type != 'Point':
                bl[-1] = np.array(nearest_points(geom.Point(bl[-1]), boundary_pol)[1], 'int').tolist()
            else:
                bl[-1] = np.array(r_point, 'int').tolist()
    return baselines
def is_tangential(l1, l2, acceptance_rate=0.3, acc_radius=-1.0, angle=0.95):

    step_size = 0.05
    tangential_score = 0
    nb_probes = 0
    # go through l1 and compare tangents with nearest point on l2
    t = 0.0

    while t < 1.0:

        p = l1.interpolate(t, normalized=True)
        p_prim = l1.interpolate(t+step_size, normalized=True)
        p_coords = np.array(p)
        p_prim_coords = np.array(p_prim)

        t += step_size
        p, q = nearest_points(p, l2)
        p_prim, q_prim = nearest_points(p_prim, l2)

        q_coords = np.array(q)
        q_prim_coords = np.array(q_prim)

        if np.all(np.isclose(p,p_prim)) or np.all(np.isclose(q,q_prim)):
            continue
        t1 = p_prim_coords - p_coords
        t2 = q_prim_coords - q_coords
        cos_alpha = np.dot(t1, t2)/(np.linalg.norm(t1)*np.linalg.norm(t2))
        if cos_alpha > angle:
            tangential_score += 1
        nb_probes += 1

    if nb_probes > 1:
        return float(tangential_score)/float(nb_probes) >= acceptance_rate
    else:
        return False
def metro_dist(from_pt, to_pts, **kwargs):
    """
    Finds distance from from_pt to nearest metro station or to_pts.
    
    from_pt : row of e.g. municipality with PROJECTED .geometry field
    to_pts (eg metro) : data frame of target points with PROJECTED .geometry field

    if additional key COMUNAS is included, distance will be taken from the centroid
    of comunas matching the correct municipality index.
    
    returns: distance (METERS, if both dataframes projected projected)
    and INDEX (second) of to_pt
    """

    # throw error if incorrect type, for whatever reason
    assert (type(from_pt.geometry)
            in [Point,
                Polygon]), "from_pt must contain point or polygon geometry"

    to_pts_geom = to_pts.geometry.tolist()
    # find nearest point to a given point
    if "comunas" in kwargs.keys():  # weighted center of comunas
        center = muni_center(from_pt["sort_ind"] + 1, kwargs["comunas"])
        r = nearest_points(center, MultiPoint(to_pts_geom))
    elif type(from_pt.geometry) == Polygon:
        r = nearest_points(from_pt.geometry.centroid, MultiPoint(to_pts_geom))
    elif type(from_pt.geometry) == Point:
        r = nearest_points(from_pt.geometry, MultiPoint(to_pts_geom))

    return r[0].distance(r[1]), to_pts_geom.index(r[1])
def extend_FaultLines(GRDECL_Data,
                      line,
                      OldFaults,
                      startfrom='StartPoint or EndPoint'):
    #extend a line from its start point or end point
    #the end point must on the boundary
    debug = 0

    if (startfrom == 'StartPoint'):
        p1, p2 = line[0], line[1]
    if (startfrom == 'EndPoint'):
        p1, p2 = line[-1], line[-2]

    if (abs(p1[0] - p2[0]) < 1e-10):
        if (debug): print("Line along Y direction")
        if (p1[1] - p2[1] < 0):  #Y- direction
            NewEndPoint = (p1[0], 0)
            NextPoint = (p1[0], p1[1] - 0.00001)
        if (p1[1] - p2[1] > 0):  #Y- direction
            NewEndPoint = (p1[0], GRDECL_Data.NY)
            NextPoint = (p1[0], p1[1] + 0.00001)
    if (abs(p1[1] - p2[1]) < 1e-10):
        if (debug): print("Line along X direction")
        if (p1[0] - p2[0] < 0):  #X- direction
            NewEndPoint = (0, p1[1])
            NextPoint = (p1[0] - 0.00001, p1[1])
        if (p1[0] - p2[0] > 0):  #X+ direction
            NewEndPoint = (GRDECL_Data.NX, p1[1])
            NextPoint = (p1[0] + 0.00001, p1[1])

    #Check is hit old fault line and upadte the new endpoint
    if (debug): print('P2P1', (p2, p1), 'ExtendSeg', NextPoint, NewEndPoint)
    ExtendedSegment = LineString([NextPoint, NewEndPoint])
    OldFaults = MultiLineString(OldFaults)
    objects = ExtendedSegment.intersection(OldFaults)

    if (objects.is_empty == False):  #We have hit point
        #print('HitGeometry',objects,objects.geom_type)
        if (objects.geom_type in ['LineString', 'Point']):
            pts = nearest_points(Point(p1), objects)
            pts = Shapely2List_MultiPoint(pts)[1]
            #print('NearestPoint',pts)
            #pts=sorted(list(objects.coords))[0]
        elif (objects.geom_type
              in ['MultiLineString', 'MultiPoint', 'GeometryCollection']):
            pts = nearest_points(Point(p1), objects)
            pts = Shapely2List_MultiPoint(pts)[1]
            #print('NearestPts',pts)
            #pts=Shapely2List_MultiLineString(objects)
            #pts=sorted([j for i in pts for j in i])[0]
        else:
            print('Unkonwn shapely type', objects.geom_type, objects)
        pts = (int(pts[0]), int(pts[1]))
        if (debug): print('HitPoints', pts)
        NewEndPoint = pts

    #NewLine=sorted(line+[NewEndPoint])
    return [NewEndPoint]
Exemple #12
0
def directionality_error(nodes, polygon):
    angles = []
    for i in range(len(nodes)):
        #edge as vector
        v1 = nodes[i - 1] - nodes[i]

        #get vector of two closest boundary points to each node
        v2 = nearest_points(polygon,Point(nodes[i][0], nodes[i][1]))[0] -\
             nearest_points(polygon,Point(nodes[i-1][0], nodes[i-1][1]))[0]

        angles.append((angle(v1, v2) % (0.5 * np.pi)))

    return 1 - (np.mean(angles) / (0.5 * np.pi))
Exemple #13
0
def passLength(candi,data_probes,data_links):
    candi2 = [candi[0]]
    for i in range(len(candi)-1):
        if len(candi2[i][1]) == 0: 
                candi2.append(candi[i+1])                # skip the samples that already has no candidate.
                continue
        probe1 = data_probes.loc[candi2[i][0]]
        probe2 = data_probes.loc[candi[i+1][0]]
        if (probe1['sampleID'] != probe2['sampleID']):
            candi2.append(candi[i+1])
            continue
        p1_speed = probe1['speed']
        p2_speed = probe2['speed']
        avg_speed = (p1_speed+p2_speed)/2
        time = 5 * (candi[i][0]-candi[i+1][0])
        length = avg_speed * time
        p1_point = Point(probe1['easting'],probe1['northing'])
        p2_point = Point(probe2['easting'],probe2['northing'])
        candi1 = []
        for j in range (len(candi[i+1][1])):
            p1_link = data_links.loc[candi[i][1][0]]
            p1_utms = p1_link["utms"][2:-2].replace("), (", "|").replace(", ", " ").replace("|", ", ")
            p1_line = wkt.loads("LINESTRING (" + p1_utms + ")")
            p1_nearest = nearest_points(p1_line, p1_point)[0]

            p2_link = data_links.loc[candi[i+1][1][j]]
            p2_utms = p2_link["utms"][2:-2].replace("), (", "|").replace(", ", " ").replace("|", ", ")
            p2_line = wkt.loads("LINESTRING (" + p2_utms + ")")
            p2_nearest = nearest_points(p2_line, p2_point)[0]
            distance = p1_nearest.distance(p2_nearest)

            p1_lim = max(p1_link['toRefSpeedLimit'],p1_link['fromRefSpeedLimit'])
            p2_lim = max(p2_link['toRefSpeedLimit'],p2_link['fromRefSpeedLimit'])
            thrsh = (max(p1_lim,p2_lim)/3.6*time)*1.1

            if length <= (thrsh+distance):
                candi1.append(candi[i+1][1][j])

        if len(candi1) > 0:
            each = []
            each.append(candi[i+1][0])
            each.append(candi1)
            candi2.append(each)
        else:
            each = []
            each.append(candi[i+1][0])
            each.append([])
            candi2.append(each)

    return candi2
Exemple #14
0
def latlon_to_reach(lat: float, lon: float) -> tuple:
    # determine the region that the point is in
    region = latlon_to_region(lat, lon)

    # switch the point because the csv's are lat/lon, backwards from what shapely expects (lon then lat)
    point = Point(float(lat), float(lon))

    # open the region csv
    df = pd.read_pickle(
        f'/app/GSP_API/geometry/{region}-comid_lat_lon_z.pickle')
    points_df = df.loc[:, "Lat":"Lon"].apply(Point, axis=1)

    # determine which point is closest
    multi_pt = MultiPoint(points_df.tolist())
    nearest_pt = nearest_points(point, multi_pt)
    reach_id = int(points_df[points_df == nearest_pt[1]].index[0])
    distance = nearest_pt[0].distance(nearest_pt[1])

    # if the nearest stream if more than .1 degrees away, you probably didn't find the right stream
    if distance > 0.11:
        raise ValueError(
            'This lat/lon pair is too far from a delineated stream. Try again or use the web interface.'
        )
    else:
        return reach_id, region, distance
def simple_line_cut(linestring, point1, dist_thres, tol, trace=True):
    from shapely.ops import nearest_points
    from shapely.ops import split
    from shapely.geometry import MultiPoint, LineString

    #Find nearest points on line:
    np1 = nearest_points(linestring, point1)

    # Return error message if points are too far away from line:
    dist1 = np1[0].distance(np1[1])
    if dist1 > dist_thres:
        if trace:
            print(
                'Point1 is', dist1,
                'units apart from line which is more than the specified distance threshold of',
                dist_thres)
        return None

    #Do split:
    split_1 = split(linestring, np1[0].buffer(tol))
    if len(list(split_1)) == 1:
        if trace:
            print('Splitting at mapped point 1 did not work')
        return None

    return list(split_1)
 def nearest_land_pos(self, point: Point, extend_dist: int = 50) -> Point:
     """Returns the nearest point inside a land exclusion zone from point
     `extend_dist` determines how far inside the zone the point should be placed"""
     if self.is_on_land(point):
         return point
     point = geometry.Point(point.x, point.y)
     nearest_points = []
     if not self.landmap:
         raise RuntimeError("Landmap not initialized")
     for inclusion_zone in self.landmap[0]:
         nearest_pair = ops.nearest_points(point, inclusion_zone)
         nearest_points.append(nearest_pair[1])
     min_distance = point.distance(
         nearest_points[0])  # type: geometry.Point
     nearest_point = nearest_points[0]  # type: geometry.Point
     for pt in nearest_points[1:]:
         distance = point.distance(pt)
         if distance < min_distance:
             min_distance = distance
             nearest_point = pt
     assert isinstance(nearest_point, geometry.Point)
     point = Point(point.x, point.y)
     nearest_point = Point(nearest_point.x, nearest_point.y)
     new_point = point.point_from_heading(
         point.heading_between_point(nearest_point),
         point.distance_to_point(nearest_point) + extend_dist)
     return new_point
Exemple #17
0
def find_nearest_point_on_line(line_pts, pts):

    if type(line_pts) is sg.LineString:
        sg_line = line_pts
    else:
        sg_line = sg.asLineString(line_pts)

    if pts.ndim == 1:
        num_pts = 1
    else:
        num_pts = np.shape(pts)[0]
    if num_pts > 1:
        min_dist = 1000
        for i_pt in range(num_pts):
            test_pt = sg.asPoint(pts[i_pt, :])
            test_dist = test_pt.distance(sg_line)
            if test_dist < min_dist:
                min_dist = test_dist
                closest_pt = test_pt

        sg_point = closest_pt
    else:
        sg_point = sg.asPoint(pts)
    try:
        near_pts = so.nearest_points(sg_line, sg_point)
    except:
        pass

    nndist = near_pts[0].distance(near_pts[1])
    nn_pt = near_pts[0]

    return nndist, nn_pt
Exemple #18
0
def get_nearest_date(x, selCables):
    selCables = selCables.loc[selCables['RFS'] <= x['d2_l1_year_perf_indicators']]
    if selCables.shape[0] > 0:
        xx = selCables.loc[selCables.geometry == nearest_points(x['geometry'], selCables.unary_union)[1]]
        return(xx.sort_values(['RFS'])['RFS'].iloc[0])
    else:
        return(-1)
Exemple #19
0
def getdestloc_simple(p, w_gdf, u, distvar):  #for students, work -> eductation

    nearestpoint = nearest_points(p, u)[1]  #get nearest point
    mindist = p.distance(nearestpoint)  #find the distance to the nearest point
    #print(mindist) degree
    sim_dist = gen_lnorm(distvar, "")
    sim_distdeg = sim_dist / 110.8

    if sim_distdeg < mindist:  # if the distance is shorter than the distance to the nearest points. take the nearest point
        sim_distdeg = mindist
        des_p = nearestpoint
        num_points = 0
        print(f'use nearest point as simulated distance is too short.')
    # else calculate a buffer and select points.
    else:
        pbuf = p.buffer(
            sim_distdeg)  # distance to degree`maybe better to project.
        pbuf.crs = {'init': 'epsg:4326', 'no_defs': True}
        worklocset = w_gdf[w_gdf.within(pbuf)]
        num_points = len(worklocset)
        print(f'sample from {num_points} points')
        workloc = worklocset.sample(n=1, replace=True, random_state=1)
        des_p = workloc.iloc[0][
            "geometry"]  #get point out of the geopandas dataframe
    return (p, des_p, num_points)
def GetCountyByCoord(lat, lon):
    point = Point(lon, lat)
    for town in towns_polygons:
        for town_polygon in towns_polygons[town]:
            if len(town_polygon) == 1:
                polygon = Polygon(town_polygon[0])
            else:
                polygon = Polygon(town_polygon)
            if polygon.contains(point):
                return town

    logger.warning(
        f'Vague point detected! Start further algorithm to check its town ')

    for town in towns_polygons:
        for town_polygon in towns_polygons[town]:
            if len(town_polygon) == 1:
                polygon = Polygon(town_polygon[0])
            else:
                polygon = Polygon(town_polygon)
            p1, _ = nearest_points(polygon, point)
            if great_circle_distance_on_earth(
                    point, p1) < 5:  # distance to shore 5km?
                logger.info(f'Success detect its town as {town}!')
                return town
    logger.warning(f'Failed to detect town!')
    return '不在台灣啦!'
Exemple #21
0
def find_separation_point(lines):

    points = []

    threshold = 0.2

    for i in range(len(lines) - 1):

        ref_line = LineString(lines[i])
        line = lines[i + 1]

        closest_points = sorted(
            [(distance(p1, (p2.x, p2.y)), p1, (p2.x, p2.y))
             for p1, p2 in [(p, nearest_points(ref_line, Point(p))[0])
                            for p in line]],
            key=lambda x: x[0])

        for j, (dist, p1, p2) in enumerate(closest_points):

            if dist > threshold or j == len(closest_points) - 1:
                points.append(((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2))
                break

    return (np.average([p[0]
                        for p in points]), np.average([p[1] for p in points]))
Exemple #22
0
def trvdir(p,candi,probe_point,data_links,data_probes):
    probe = data_probes.loc[p]
    candi2 = []
    for i in range(len(candi)):
        link = data_links.loc[candi[i]]
        utms = link["utms"][2:-2].replace("), (", "|").replace(", ", " ").replace("|", ", ")
        line = wkt.loads("LINESTRING (" + utms + ")")
        nearest = nearest_points(line, probe_point)[0]
        #link_distance = nearest.distance(probe_point)
        ref_node = Point(line.coords[0][0], line.coords[0][1])
        # ref_distance = ref_node.distance(probe_point)
        pro_link_dis = nearest.distance(ref_node)

        # Update dataframe attributes
        data_probes.loc[p, "linkPVID"] = link["linkPVID"]
        #data_probes.loc[p, "distFromLink"] = link_distance
        #data_probes.loc[p, "distFromRef"] = ref_distance
        data_probes.loc[p,"distBetRP"] = pro_link_dis

        # Calculate the orientation relative to the ref node
        radians = math.atan2(ref_node.y - probe_point.y, ref_node.x - probe_point.x)
        ref_node_direction = int(math.degrees(radians))
        if ref_node_direction <= 0:
            ref_node_direction = ref_node_direction + 360
        if abs(ref_node_direction - probe["heading"]) <= 90:
            data_probes.loc[p, "direction"] = 'T'
        else:
            data_probes.loc[p, "direction"] = 'F'
        s_direc = data_probes.loc[p, "direction"] 
        l_direc = link["directionOfTravel"]
        if ~((l_direc != 'B') & (s_direc != l_direc)):   # only keep the segment candidates whose directionOfTravel is conformed with the sample's current travel direction.    
                candi2.append(candi[i])
    return candi2
def chunk_worker(left_spec, right_spec, pairs_slice):

    # recover the SharedMemory bloc
    left_shm = SharedMemory(left_spec['name'])
    right_shm = SharedMemory(right_spec['name'])
    # Create the np.recarray from the buffer of the shared memory
    left_arr = np.recarray(shape=left_spec['shape'],
                           dtype=left_spec['dtype'],
                           buf=left_shm.buf)
    right_arr = np.recarray(shape=right_spec['shape'],
                            dtype=right_spec['dtype'],
                            buf=right_shm.buf)

    #print (left_arr[0][2], right_arr[0][2])

    results = []
    for idx_pair in pairs_slice:
        geom1 = wkt.loads(left_arr[idx_pair[0]][2])
        geom2 = wkt.loads(right_arr[idx_pair[1]][2])

        pt1, pt2 = ops.nearest_points(geom1, geom3)

        dist, a1, a2 = V_inv((pt1.y, pt1.x), (pt2.y, pt2.x))

        dist = dist * 1000  #m

        results.append((idx_pair[0], idx_pair[1], dist))

    return results
Exemple #24
0
def getNearestWay(query, project, inputCoord):
    """

    @param query:
    @param project:
    @param inputCoord:
    @return:
    """
    lineStringDict = {}
    for i in query.features:
        # Transform from WGS 1984 to the projection, this avoids getting degrees in results
        shape = transform(project, LineString(i["geometry"]["coordinates"]))
        # Calculate nearest point between the input coordinate and the way geom
        nearestPt = nearest_points(inputCoord, shape)[1]
        # Get the distance to the nearest point from the input coordinate
        distToPt = nearestPt.distance(inputCoord)
        # Build dict with results, OSM IDs are the top level keys
        lineStringDict[i["id"]] = {"name": i["properties"]["name"], "shape": shape, "nearestPt": nearestPt,
                                   "distToPt": distToPt}

    lowestVal = ["", 99999]
    # Get nearest way name by looping over IDs in dict
    for i in lineStringDict.keys():
        if lineStringDict[i]["distToPt"] < lowestVal[1]:
            lowestVal[0] = lineStringDict[i]["name"]
            lowestVal[1] = lineStringDict[i]["distToPt"]
    return lowestVal
def check_double_points(gdf, radius=0.001, id_column='id'):
    """

    :param gdf:
    :param radius:
    :param id_column:
    :return:
    """

    l_ids = []
    count = 0

    for r, c in gdf.iterrows():

        point = c['geometry']
        gdf_other = gdf.drop([r])
        other_points = cascaded_union(gdf_other['geometry'])

        # x1 = nearest_points(point, other_points)[0]
        x2 = nearest_points(point, other_points)[1]

        if point.distance(x2) <= radius:
            l_ids.append(c[id_column])
            print('Node ', c[id_column], ' has a near neighbour!', 'Distance ',
                  point.distance(x2))
            count += 1

    print('')
    print('Number of duplicated points: ', count)

    return l_ids
Exemple #26
0
def point_at_intersect(gdf_cross, gdf_line):
    gdf_cross = check_gdf(gdf_cross)
    gdf_line = check_gdf(gdf_line)

    df_points = pd.DataFrame([],
                             columns=[gdf_line.index],
                             index=gdf_cross.index,
                             dtype='object')
    for line, linerow in gdf_line.iterrows():
        geolist = []
        for index, row in gdf_cross.iterrows():
            interpoint = row.geometry.intersection(linerow.geometry)
            if interpoint.geom_type == 'Point':
                geolist.append(interpoint)
            else:
                nearest_geoms = nearest_points(Point(row['midX'], row['midY']),
                                               interpoint)
                geolist.append(nearest_geoms[1])
        # df_points[line]=gpd.GeoSeries([row[1].geometry.intersection(linerow.geometry) for row in gdf_cross.iterrows()])
        workpath = os.getenv(
            'surfdrive'
        ) + "\\Documents\\DATA\\Netherlands\\main channel\\main_channelbedlevel\\bed_level_data\\"

        gpd.GeoDataFrame(gdf_cross.rkm, geometry=geolist).to_file(
            os.path.join(workpath, 'worktmp', 'RL_' + str(line) + '.shp'))
        df_points[line] = gpd.GeoSeries(geolist, index=gdf_cross.index)

    return df_points
Exemple #27
0
def query_k_nearest_road_segments(edge_idx, point, k):
    """
    query k-nearest road segments of a given point
    :param edge_idx: the road segments r-tree index
    :param point: the given point
    :param k: the number of segments needed to query
    :return: k candidates as a pandas DataFrame
    """
    candidates = pd.DataFrame(columns=('distance', 'from', 'to', 'proj_point',
                                       'road'))
    hits = edge_idx.nearest((point.x, point.y, point.x, point.y),
                            k,
                            objects=True)
    for item in hits:
        results = nearest_points(point, item.object['geometry'])
        d = point.distance(results[1])
        s = pd.Series({
            'distance': d,
            'from': item.object['from'],
            'to': item.object['to'],
            'proj_point': results[1],
            'road': item.object
        })
        candidates = candidates.append(s, ignore_index=True)
    # candidates['observation prob'] = candidates.apply(lambda row: normal_distribution())
    candidates.sort_values(by='distance', axis=0, inplace=True)
    return candidates
Exemple #28
0
def get_distance_water(gdf, gdf_water):
    """
    Function to calculate distance to nearest water body
    
    Input:
    gdf: Geodataframe (Ideally a grid network of the city)
    gdf_water : Water mask geodataframe
    
    Returns:
    Geodataframe with column 'dist_to_water' added to it
    """
    
    print("Populating distance to water!!")
    gdf_land = gdf.copy()
    gdf_water.to_crs(epsg=out_proj, inplace=True)
    gdf_land.to_crs(epsg=out_proj, inplace=True)
    
    water_dist = []
    
    dest_water = MultiPoint([i.centroid for i in gdf_water.geometry])
    
    for i in gdf_land.index:
        if i % 1000 == 0:
            print("{0} of {1} rows processed" .format(i, len(gdf_land)))

        temp_cent = gdf_land.geometry[i].centroid
        nearest_geoms = nearest_points(temp_cent, dest_water)
        water_dist.append(nearest_geoms[0].distance(nearest_geoms[1]))
    
    gdf['dist_to_water'] = water_dist
    
    return gdf
Exemple #29
0
def get_nearest_row_id(id_done, pt_ref, df_route):

    if (id_done < 0):
        id_done = 0

    id_until = int(round(id_done + (len(df_route) * 0.1)))
    if id_until < 1:
        id_until = 1
    id_until = len(df_route) if id_until > len(df_route) else id_until
    df_route_slice = df_route[id_done:id_until]
    '''
	print('id_done', id_done)
	print (pt_ref)
	display(df_route.head())
	display (df_route_slice.head())
	'''
    '''
	print('pts3')
	print (pts3)
	print ("pt_ref")
	print (pt_ref)
	'''
    pts3 = df_route_slice.geometry.unary_union
    nearest = df_route_slice.geometry == nearest_points(pt_ref, pts3)[1]

    list_ids = df_route_slice[nearest].id.values

    list_ids.sort()
    for i in list_ids:
        if i >= id_done:
            return i

    return -1
Exemple #30
0
 def test_nearest(self):
     first, second = nearest_points(
                     Point(0, 0).buffer(1.0), Point(3, 0).buffer(1.0))
     self.assertAlmostEqual(first.x, 1.0, 7)
     self.assertAlmostEqual(second.x, 2.0, 7)
     self.assertAlmostEqual(first.y, 0.0, 7)
     self.assertAlmostEqual(second.y, 0.0, 7)
Exemple #31
0
def get_nearest_station(poi=Point(restaurants_points[0])):
    stations_mp = MultiPoint(stations_points)
    testpoint = Point(nearest_points(poi, stations_mp)[0])
    soi = restaurants.Station[(restaurants.Lat == testpoint.y)
                              & (restaurants.Long == testpoint.x)]
    soi = list(soi)[0]
    return (soi)