Ejemplo n.º 1
0
def get_adjusted_routing_location(latLon,
                                  graph=None,
                                  edge_gdf=None,
                                  node_gdf=None):
    wgs_point = geom_utils.get_point_from_lat_lon(latLon)
    etrs_point = geom_utils.project_to_etrs(wgs_point)
    point_buffer = etrs_point.buffer(90)
    buffer_random_coords = point_buffer.exterior.coords[0]
    new_point = Point(buffer_random_coords)
    point_xy = geom_utils.get_xy_from_geom(new_point)
    try:
        node = rt.get_nearest_node(graph,
                                   point_xy,
                                   edge_gdf,
                                   node_gdf,
                                   logging=False)
        node_geom = nw.get_node_geom(graph, node['node'])
        node_distance = round(node_geom.distance(etrs_point))
        node_geom_wgs = geom_utils.project_to_wgs(node_geom)
        node_latLon = geom_utils.get_lat_lon_from_geom(node_geom_wgs)
        if (node_distance < 130):
            return node_latLon
    except Exception:
        print('no adjusted origin/destination found')
        return latLon
    print('no adjusted origin/destination found')
    return latLon
Ejemplo n.º 2
0
def get_new_node_attrs(graph, point):
    new_node_id = get_new_node_id(graph)
    wgs_point = geom_utils.project_to_wgs(point)
    geom_attrs = {
        **geom_utils.get_xy_from_geom(point),
        **geom_utils.get_lat_lon_from_geom(wgs_point)
    }
    return {'id': new_node_id, **geom_attrs}
Ejemplo n.º 3
0
def parse_itin_attributes(itins, from_id, to_id, utilization=1):
    '''
    Function for parsing route geometries got from Digitransit Routing API. 
    Coordinates are decoded from Google Encoded Polyline Algorithm Format.
    Returns
    -------
    <list of dictionaries>
        List of itineraries as dictionaries
    '''
    # walk_gdfs = []
    stop_dicts = []
    # print('itins:', len(itins), 'weight(yht):', weight, 'itin_weight:', itin_weight)
    for itin in itins:
        walk_leg = itin['legs'][
            0]  #TODO fix when origin is at the PT stop, first leg will not be walk but PT (BUS etc.)
        try:
            pt_leg = itin['legs'][1]
        except IndexError:
            pt_leg = {'mode': 'none'}
        geom = walk_leg['legGeometry']['points']
        # parse coordinates from Google Encoded Polyline Algorithm Format
        decoded = polyline.decode(geom)
        # swap coordinates (y, x) -> (x, y)
        coords = [point[::-1] for point in decoded]
        walk = {}
        walk['utilization'] = utilization
        walk['from_axyind'] = from_id
        walk['to_id'] = to_id
        walk['to_pt_mode'] = pt_leg['mode']
        walk['DT_geom'] = geom_utils.create_line_geom(coords)
        walk['DT_walk_dist'] = round(walk_leg['distance'], 2)
        walk['DT_origin_latLon'] = geom_utils.get_lat_lon_from_coords(
            coords[0])
        # walk['first_Point'] = Point(coords[0])
        # walk['DT_last_Point'] = Point(coords[len(coords)-1])
        to_stop = walk_leg['to']['stop']
        walk['stop_id'] = to_stop['gtfsId'] if to_stop != None else ''
        # walk['stop_desc'] = to_stop['desc'] if to_stop != None else ''
        DT_dest_point = geom_utils.get_point_from_lat_lon(
            to_stop) if to_stop != None else Point(coords[len(coords) - 1])
        walk['DT_dest_Point'] = DT_dest_point
        walk['dest_latLon'] = geom_utils.get_lat_lon_from_geom(DT_dest_point)
        # parent_station = to_stop['parentStation'] if to_stop != None else None
        # walk['stop_p_id'] = parent_station['gtfsId'] if parent_station != None else ''
        # walk['stop_p_name'] = parent_station['name'] if parent_station != None else ''
        # walk['stop_p_Point'] = geom_utils.get_point_from_lat_lon(parent_station) if parent_station != None else ''
        # cluster = to_stop['cluster'] if to_stop != None else None
        # walk['stop_c_id'] = cluster['gtfsId'] if cluster != None else ''
        # walk['stop_c_name'] = cluster['name'] if cluster != None else ''
        # walk['stop_c_Point'] = geom_utils.get_point_from_lat_lon(cluster) if cluster != None else ''
        # convert walk dictionary to GeoDataFrame
        # walk_proj = reproject_dict_geoms(walk)
        # walk_data = dict_values_as_lists(walk_proj)
        # walk_gdf = gpd.GeoDataFrame(data=walk_data, geometry=walk_data['path_geom'], crs=from_epsg(3879))
        # walk_gdfs.append(walk_gdf)
        stop_dicts.append(walk)
    # walk_gdf = pd.concat(walk_gdfs).reset_index(drop=True)
    return stop_dicts
Ejemplo n.º 4
0
def get_origin_lat_lon():
    # read locations for routing tests (in WGS)
    locations = gpd.read_file('data/test/test_locations_qp_tests.geojson')
    locations['latLon'] = [
        geom_utils.get_lat_lon_from_geom(geom)
        for geom in locations['geometry']
    ]
    origin = locations.query("name == 'Koskela'").copy()
    return list(origin['latLon'])[0]
Ejemplo n.º 5
0
def get_test_ODs():
    # read OD pairs for routing tests (in WGS)
    ods = gpd.read_file('data/test/test_OD_lines.geojson')
    ods['orig_point'] = [
        geom.interpolate(0, normalized=True) for geom in ods['geometry']
    ]
    ods['dest_point'] = [
        geom.interpolate(1, normalized=True) for geom in ods['geometry']
    ]
    ods['orig_latLon'] = [
        geom_utils.get_lat_lon_from_geom(geom) for geom in ods['orig_point']
    ]
    ods['dest_latLon'] = [
        geom_utils.get_lat_lon_from_geom(geom) for geom in ods['dest_point']
    ]
    od_dicts = ods.to_dict(orient='records')
    od_dict = {}
    for od in od_dicts:
        od_dict[int(od['OD'])] = od
    return od_dict
Ejemplo n.º 6
0
def get_valid_distr_geom(districts, workplaces_distr_join):
    workplace_distr_g = workplaces_distr_join.groupby('id_distr')

    district_dicts = []

    for idx, distr in districts.iterrows():
        # if (distr['id_distr'] != '091_OULUNKYLÄ'):
        #     continue
        d = {
            'id_distr': distr['id_distr'],
            'geom_distr_poly': distr['geom_distr_poly']
        }
        try:
            distr_works = workplace_distr_g.get_group(distr['id_distr'])
            distr_works = gpd.GeoDataFrame(distr_works,
                                           geometry='geom_work',
                                           crs=from_epsg(3067))
            works_convex_poly = distr_works[
                'geom_work'].unary_union.convex_hull
            # print(works_convex_poly)
            works_convex_poly_buffer = works_convex_poly.buffer(20)
            works_center_point = works_convex_poly_buffer.centroid
            # print(works_center_point)
            distr_works['work_center_dist'] = [
                round(geom.distance(works_center_point))
                for geom in distr_works['geom_work']
            ]
            distr_works = distr_works.sort_values(by='work_center_dist')
            # print(distr_works.head(70))
            center_work = distr_works.iloc[0]
            d['work_center'] = center_work['geom_work']
            d['has_works'] = 'yes'
        except Exception:
            d['work_center'] = distr['geom_distr_poly'].centroid
            d['has_works'] = 'no'
        district_dicts.append(d)

    districts_gdf = gpd.GeoDataFrame(district_dicts,
                                     geometry='geom_distr_poly',
                                     crs=from_epsg(3067))
    districts_gdf['distr_latLon'] = [
        geom_utils.get_lat_lon_from_geom(
            geom_utils.project_to_wgs(geom, epsg=3067))
        for geom in districts_gdf['work_center']
    ]
    return districts_gdf
Ejemplo n.º 7
0
nodes_sind = node_gdf.sindex
print('Spatial index built.')

#%% read YKR work commute data
commutes = pd.read_csv('data_ykr/T06_tma_e_TOL2008_2016_hel.csv')
# commutes['axyind'] = [int(xyind) for xyind in commutes['axyind']]
# commutes['txyind'] = [int(xyind) for xyind in commutes['txyind']]
# commutes = commutes.loc[commutes['akunta'] == 91]
# commutes = commutes.loc[commutes['sp'] == 0]
# commutes.to_csv('data_ykr/T06_tma_e_TOL2008_2016_hel.csv')
commutes['geom_home'] = commutes.apply(lambda row: Point(row['ax'], row['ay']),
                                       axis=1)
commutes['geom_work'] = commutes.apply(lambda row: Point(row['tx'], row['ty']),
                                       axis=1)
commutes['home_latLon'] = [
    geom_utils.get_lat_lon_from_geom(geom_utils.project_to_wgs(geom,
                                                               epsg=3067))
    for geom in commutes['geom_home']
]
commutes['work_latLon'] = [
    geom_utils.get_lat_lon_from_geom(geom_utils.project_to_wgs(geom,
                                                               epsg=3067))
    for geom in commutes['geom_work']
]
commutes = commutes[[
    'txyind', 'axyind', 'geom_home', 'geom_work', 'home_latLon', 'work_latLon',
    'yht'
]]
commutes.head()

#%% read grid
grid = files.get_statfi_grid()
Ejemplo n.º 8
0
def get_valid_latLon_for_DT(latLon,
                            distance=60,
                            datetime=None,
                            graph=None,
                            edge_gdf=None,
                            node_gdf=None):
    # try if initial latLon works
    try:
        itins = DT_routing.get_route_itineraries(latLon, {
            'lat': 60.278320,
            'lon': 24.853545
        },
                                                 '1.16666',
                                                 datetime,
                                                 itins_count=3,
                                                 max_walk_distance=2500)
        if (len(itins) > 0):
            print('initial latLon works wiht DT')
            return latLon
    except Exception:
        print('proceed to finding altenative latLon for DT')
    # if original latLon did not work, proceed to finding alternative latLon
    wgs_point = geom_utils.get_point_from_lat_lon(latLon)
    etrs_point = geom_utils.project_to_etrs(wgs_point)
    # create a circle for finding alternative points within a distanece from the original point
    point_buffer = etrs_point.buffer(distance)
    circle_coords = point_buffer.exterior.coords
    # find four points at the buffer distance to try as alternative points in routing
    for n in [0, 1, 2, 3]:
        circle_quarter = len(circle_coords) / 4
        circle_place = math.floor(n * circle_quarter)
        circle_point_coords = circle_coords[circle_place]
        circle_point = Point(circle_point_coords)
        point_xy = geom_utils.get_xy_from_geom(circle_point)
        try:
            # find nearest node in the network
            node = rt.get_nearest_node(graph,
                                       point_xy,
                                       edge_gdf,
                                       node_gdf,
                                       logging=False)
            node_geom = nw.get_node_geom(graph, node['node'])
            node_distance = round(node_geom.distance(etrs_point))
            node_geom_wgs = geom_utils.project_to_wgs(node_geom)
            node_latLon = geom_utils.get_lat_lon_from_geom(node_geom_wgs)
            # try DT routing to node location
            if (node_distance < 90):
                time.sleep(0.2)
                try:
                    itins = DT_routing.get_route_itineraries(
                        node_latLon, {
                            'lat': 60.278320,
                            'lon': 24.853545
                        },
                        '1.16666',
                        datetime,
                        itins_count=3,
                        max_walk_distance=2500)
                    if (len(itins) > 0):
                        print('found DT valid latLon at distance:',
                              node_distance, '-', node_latLon)
                        return node_latLon
                    else:
                        continue
                except Exception:
                    continue
        except Exception:
            print('no node/edge found')
            continue
    print('no DT valid latLon found')
    return None