Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions examples/development.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@
fbn.settings.radius = 1000

fbn.fixbikenet(
city_query="Frederiksberg Municipality",
city_query="Turin center",
min_gap_length = 0,
max_gap_length = 100,
num_gaps = 20,
import_files={
'city_boundary': "./tests/test_data/frederiksberg_boundary.geojson",
'city_boundary': "./tests/test_data/turin_center_boundary.geojson",
'trip_data': "./tests/test_data/turin_trips.csv",
# 'street_network': "./tests/test_data/frederiksberg_streetbike_network.gpkg",
},
)
25 changes: 21 additions & 4 deletions fixbikenet/fixbikenet.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Main procedure for running `fixbikenet`."""

import bikenetlib as bnl
from . import constants, settings, osm, _overpass
import os
import geopandas as gpd
Expand All @@ -24,6 +25,7 @@
_validate_parameters,
_validate_settings,
add_point_data_to_net,
add_trip_data_to_net,
compute_local_betweenness_centrality,
create_gdf_with_geoms,
download_network,
Expand Down Expand Up @@ -87,9 +89,9 @@ def fixbikenet(

- 'city_boundary' : None or str, default None
If not set to None, the study area is selected from the
(Multi)Polygon provided in the city_boundary shape or gpkg file,
ideally in unprojected latitude-longitude degrees (EPSG:4326), but
EPSG:3857 also works.
(Multi)Polygon provided in the city_boundary shape, gpkg, or
geojson file, ideally in unprojected latitude-longitude degrees
(EPSG:4326), but EPSG:3857 also works.
- 'street_network' : str | None, default None
If not set to None, the street network is loaded from this file.
For best results, this network should encompass both car and
Expand All @@ -106,6 +108,13 @@ def fixbikenet(
from this file, representing point events like traffic crashes or
citizen feedback to improve bike infrastructure. Must be a gpkg or geojson file in unprojected CRS EPSG:4326 containing only point objects, optionally with an int ``num`` column that encodes the
number of point events. The data set is used to re-prioritize the ordering of the network gaps, controlled with `settings.import_data_impact`.
- 'trip_data' : None or str, default None
If not set to None, an additional data set of trips will be loaded
from this file, representing trip events for prioritizing bike
infrastructure growth. Must be a csv file in unprojected CRS EPSG:4326 containing the following fields:
``o_lat, o_lon, d_lat, d_lon``. Optionally there can be an int
``num`` field that encodes the number of trips between each origin
and destination.

Returns
-------
Expand All @@ -125,7 +134,7 @@ def fixbikenet(
_print_header(city_query)

### Import data files
num_data_files, point_data, _ = _import_data_files(import_files) # trip_data set to _. To do in the future.
num_data_files, point_data, trip_data = _import_data_files(import_files)

# Get city boundary
if import_files['city_boundary']:
Expand Down Expand Up @@ -198,6 +207,14 @@ def fixbikenet(
G_lengths = nx.get_edge_attributes(G, "length")
nx.set_edge_attributes(G, G_lengths, "distance")
nx.set_edge_attributes(G, G_lengths, "distance_weighted")

if trip_data is not None:
G_trips = add_trip_data_to_net(trip_data, nx.Graph(ox.project_graph(nx.MultiDiGraph(G)), to_crs=constants._CRS_CALCULATIONS), matching_distance=settings.import_trip_data_snap_distance)
trips = nx.get_edge_attributes(G_trips, 'num_trips')
print(trips)
sys.exit()
ebc = {key: value * trips[key] for key, value in ebc.items()}

# Add point data to edges
if point_data is not None:
G_gaps = nx.MultiGraph(G.subgraph(set(n for nlist in found_gaps_nsp for n in nlist))) # To do once pythonmin>=3.15: *nlist for nlist in found_gaps_nsp
Expand Down
4 changes: 4 additions & 0 deletions fixbikenet/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
import_point_data_snap_distance : int, default 100
Maximum distance between point data and network links for snapping, in
meters.
import_trip_data_snap_distance : int, default 500
Maximum distance between trip data and network links for snapping, in
meters.
import_path : str
Path to import files (as defined in `fixbikenet`'s import_files parameter).
radius : int, default 2500
Expand All @@ -25,6 +28,7 @@
export_path = "./results/"
import_data_impact = 10000
import_point_data_snap_distance = 100
import_trip_data_snap_distance = 500
import_path = "./"

radius = 2500
Expand Down
94 changes: 89 additions & 5 deletions fixbikenet/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import shapely
from shapely.geometry import LineString, Point
from shapely.strtree import STRtree
from pyproj import Transformer
from tqdm import tqdm


Expand Down Expand Up @@ -136,6 +137,83 @@ def initialize_progress_bar(desc_string, total=1, unit="step"):
disable=settings.silent,
)

def add_trip_data_to_net(trips, A, matching_distance=settings.import_trip_data_snap_distance):
"""Match trip data to network edges.

First, match origin and destination points given in trips to the nodes.
Only consider trips where both origins and nodes are matched within
`matching_distance`. Then, for each trip, find the shortest path over the
edges from matched origin node to matched destination node, and add 1 (or
optionally ``num`` if column provided in trips) to the affected edges.

Parameters
----------
trips : pandas DataFrame
A dataframe of unprojected origin-destination coordinates (columns:
``o_lat, o_lon, d_lat, d_lon``), with each row encoding a trip, in
unprojected CRS EPSG:4326. Optional with a column ``num`` containing an
integer. This could be (number of) trip events. If ``num`` column is
not provided, assumes 1 per trip.
A: networkx.graph
Graph to match trip data to, in projected crs
`constants._CRS_CALCULATIONS`.
matching_distance : int, default `settings.import_trip_data_snap_distance`
Matching distance in meters. Set via
`settings.import_trip_data_snap_distance`.

Returns
-------
graph_with_data : networkx.graph
The same graph created from triangulation edges list, but with a new
edge attribute 'num_trips' populated with the summed up ``num`` values
of all trips where both origins and destinations could be matched to
the closest network nodes within `matching_distance`.
"""
graph_with_data = A.copy()
transformer = Transformer.from_crs("EPSG:4326", constants._CRS_CALCULATIONS, always_xy=True)

# If column "num" is not provided assume 1 trip per origin-destination (OD) pair
if 'num' in trips.columns:
nums = trips['num']
else:
nums = [1] * len(trips)

# Project trip data
trips_projected = trips.copy()
trips_projected['o_lon'], trips_projected['o_lat'] = transformer.transform(trips['o_lon'], trips['o_lat'])
trips_projected['d_lon'], trips_projected['d_lat'] = transformer.transform(trips['d_lon'], trips['d_lat'])

# Match given origins and destinations to the closest nodes in the network
o_nodes, o_distances = ox.distance.nearest_nodes(graph_with_data, trips_projected['o_lon'], trips_projected['o_lat'], return_dist=True)
d_nodes, d_distances = ox.distance.nearest_nodes(graph_with_data, trips_projected['d_lon'], trips_projected['d_lat'], return_dist=True)

# Add number of trips to graph
trip_dict = dict(zip(graph_with_data.edges, [0] * len(graph_with_data.edges)))

for o_node, o_distance, d_node, d_distance, num in zip(o_nodes, o_distances, d_nodes, d_distances, nums):
# If:
# - origin and destination are snapped to the same node, or
# - origin is >500m away from the snapped node, or
# - destination is >500m away from the snapped node
# no trips are added
if o_node == d_node or o_distance > matching_distance or d_distance > matching_distance:
continue

# Get shortest path between the snapped orgin and destination nodes
path = nx.shortest_path(graph_with_data, source=o_node, target=d_node, weight="distance")
path_edges = list(zip(path[:-1], path[1:]))

# Add the number of trips to each edge of the shortest path
for i, edge_id in enumerate(path_edges):
if edge_id in trip_dict:
trip_dict[edge_id] += num
else:
edge_id = (path[i + 1], path[i]) # Inverse node order
if edge_id in trip_dict:
trip_dict[edge_id] += num

nx.set_edge_attributes(graph_with_data, trip_dict, 'num_trips')
return graph_with_data

def download_network(city_query, network_type='drive', custom_filter=None, retain_all=True, city_boundary_geometry=None):
"""Download and prepare a street network from OSM via OSMnx.
Expand Down Expand Up @@ -171,16 +249,22 @@ def download_network(city_query, network_type='drive', custom_filter=None, retai
# Fetch street network data from osmnx
if city_boundary_geometry is None:
g = ox.graph_from_place(
city_query, network_type=network_type, custom_filter=custom_filter, retain_all=retain_all
city_query,
network_type=network_type,
custom_filter=custom_filter,
retain_all=retain_all,
simplify=False
)
else:
g = ox.graph_from_polygon(
city_boundary_geometry, network_type=network_type, custom_filter=custom_filter, retain_all=retain_all
city_boundary_geometry,
network_type=network_type,
custom_filter=custom_filter,
retain_all=retain_all,
simplify=False
)

g_undir = g.to_undirected().copy() # convert to undirected (dropping OSMnx keys!)

return g_undir
return g


def import_network(street_network):
Expand Down
8 changes: 8 additions & 0 deletions tests/test_data/turin_center_boundary.geojson
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"type": "FeatureCollection",
"name": "turin_it",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 7.614512,45.066065 ], [ 7.614512,45.090278 ], [ 7.655497,45.090278 ], [ 7.655497,45.066065 ], [ 7.614512,45.066065 ] ] ] } }
]
}
Loading
Loading