ObjectNat 1.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- objectnat/__init__.py +9 -0
- objectnat/_api.py +14 -0
- objectnat/_config.py +43 -0
- objectnat/_version.py +1 -0
- objectnat/methods/__init__.py +0 -0
- objectnat/methods/coverage_zones/__init__.py +3 -0
- objectnat/methods/coverage_zones/graph_coverage.py +105 -0
- objectnat/methods/coverage_zones/radius_voronoi_coverage.py +39 -0
- objectnat/methods/coverage_zones/stepped_coverage.py +136 -0
- objectnat/methods/isochrones/__init__.py +1 -0
- objectnat/methods/isochrones/isochrone_utils.py +167 -0
- objectnat/methods/isochrones/isochrones.py +282 -0
- objectnat/methods/noise/__init__.py +3 -0
- objectnat/methods/noise/noise_init_data.py +10 -0
- objectnat/methods/noise/noise_reduce.py +155 -0
- objectnat/methods/noise/noise_simulation.py +453 -0
- objectnat/methods/noise/noise_simulation_simplified.py +222 -0
- objectnat/methods/point_clustering/__init__.py +1 -0
- objectnat/methods/point_clustering/cluster_points_in_polygons.py +115 -0
- objectnat/methods/provision/__init__.py +1 -0
- objectnat/methods/provision/provision.py +213 -0
- objectnat/methods/provision/provision_exceptions.py +59 -0
- objectnat/methods/provision/provision_model.py +323 -0
- objectnat/methods/utils/__init__.py +1 -0
- objectnat/methods/utils/geom_utils.py +173 -0
- objectnat/methods/utils/graph_utils.py +306 -0
- objectnat/methods/utils/math_utils.py +32 -0
- objectnat/methods/visibility/__init__.py +6 -0
- objectnat/methods/visibility/visibility_analysis.py +485 -0
- objectnat-1.3.3.dist-info/METADATA +202 -0
- objectnat-1.3.3.dist-info/RECORD +33 -0
- objectnat-1.3.3.dist-info/WHEEL +4 -0
- objectnat-1.3.3.dist-info/licenses/LICENSE.txt +28 -0
objectnat/__init__.py
ADDED
objectnat/_api.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# pylint: disable=unused-import,wildcard-import,unused-wildcard-import
|
|
2
|
+
|
|
3
|
+
from .methods.coverage_zones import get_graph_coverage, get_radius_coverage, get_stepped_graph_coverage
|
|
4
|
+
from .methods.isochrones import get_accessibility_isochrone_stepped, get_accessibility_isochrones
|
|
5
|
+
from .methods.noise import calculate_simplified_noise_frame, simulate_noise
|
|
6
|
+
from .methods.point_clustering import get_clusters_polygon
|
|
7
|
+
from .methods.provision import clip_provision, get_service_provision, recalculate_links
|
|
8
|
+
from .methods.utils import gdf_to_graph, graph_to_gdf
|
|
9
|
+
from .methods.visibility import (
|
|
10
|
+
calculate_visibility_catchment_area,
|
|
11
|
+
get_visibilities_from_points,
|
|
12
|
+
get_visibility,
|
|
13
|
+
get_visibility_accurate,
|
|
14
|
+
)
|
objectnat/_config.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
from loguru import logger
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Config:
|
|
8
|
+
"""
|
|
9
|
+
A configuration class to manage global settings for the application, such as Overpass API URL,
|
|
10
|
+
timeouts, and logging options.
|
|
11
|
+
|
|
12
|
+
Attributes
|
|
13
|
+
----------
|
|
14
|
+
enable_tqdm_bar : bool
|
|
15
|
+
Enables or disables progress bars (via tqdm). Defaults to True.
|
|
16
|
+
logger : Logger
|
|
17
|
+
Logging instance to handle application logging.
|
|
18
|
+
|
|
19
|
+
Methods
|
|
20
|
+
-------
|
|
21
|
+
change_logger_lvl(lvl: Literal["TRACE", "DEBUG", "INFO", "WARN", "ERROR"])
|
|
22
|
+
Changes the logging level to the specified value.
|
|
23
|
+
set_enable_tqdm(enable: bool)
|
|
24
|
+
Enables or disables progress bars in the application.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
enable_tqdm_bar=True,
|
|
30
|
+
):
|
|
31
|
+
self.enable_tqdm_bar = enable_tqdm_bar
|
|
32
|
+
self.logger = logger
|
|
33
|
+
|
|
34
|
+
def change_logger_lvl(self, lvl: Literal["TRACE", "DEBUG", "INFO", "WARN", "ERROR"]):
|
|
35
|
+
self.logger.remove()
|
|
36
|
+
self.logger.add(sys.stderr, level=lvl)
|
|
37
|
+
|
|
38
|
+
def set_enable_tqdm(self, enable: bool):
|
|
39
|
+
self.enable_tqdm_bar = enable
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
config = Config()
|
|
43
|
+
config.change_logger_lvl("INFO")
|
objectnat/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
VERSION = "1.3.3"
|
|
File without changes
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
import geopandas as gpd
|
|
4
|
+
import networkx as nx
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from pyproj.exceptions import CRSError
|
|
7
|
+
from shapely import Point, concave_hull
|
|
8
|
+
|
|
9
|
+
from objectnat.methods.utils.graph_utils import get_closest_nodes_from_gdf, reverse_graph
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_graph_coverage(
|
|
13
|
+
gdf_to: gpd.GeoDataFrame,
|
|
14
|
+
nx_graph: nx.Graph,
|
|
15
|
+
weight_type: Literal["time_min", "length_meter"],
|
|
16
|
+
weight_value_cutoff: float = None,
|
|
17
|
+
zone: gpd.GeoDataFrame = None,
|
|
18
|
+
):
|
|
19
|
+
"""
|
|
20
|
+
Calculate coverage zones from source points through a graph network using Dijkstra's algorithm
|
|
21
|
+
and Voronoi diagrams.
|
|
22
|
+
|
|
23
|
+
The function works by:
|
|
24
|
+
1. Finding nearest graph nodes for each input point
|
|
25
|
+
2. Calculating all reachable nodes within cutoff distance using Dijkstra
|
|
26
|
+
3. Creating Voronoi polygons around graph nodes
|
|
27
|
+
4. Combining reachability information with Voronoi cells
|
|
28
|
+
5. Clipping results to specified zone boundary
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
gdf_to (gpd.GeoDataFrame):
|
|
32
|
+
Source points to which coverage is calculated.
|
|
33
|
+
|
|
34
|
+
nx_graph (nx.Graph):
|
|
35
|
+
NetworkX graph representing the transportation network.
|
|
36
|
+
|
|
37
|
+
weight_type:
|
|
38
|
+
Type of edge weight to use for path calculation:
|
|
39
|
+
|
|
40
|
+
- ``"time_min"``: Edge travel time in minutes
|
|
41
|
+
- ``"length_meter"``: Edge length in meters
|
|
42
|
+
|
|
43
|
+
weight_value_cutoff (float):
|
|
44
|
+
Maximum weight value for path calculations (e.g., max travel time/distance).
|
|
45
|
+
|
|
46
|
+
zone (gpd.GeoDataFrame):
|
|
47
|
+
Boundary polygon to clip the resulting coverage zones. If None, concave hull of reachable nodes will be used.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
gpd.GeoDataFrame:
|
|
51
|
+
GeoDataFrame with coverage zones polygons, each associated with its source point, returns in the same CRS
|
|
52
|
+
as original gdf_from.
|
|
53
|
+
|
|
54
|
+
Notes:
|
|
55
|
+
- The graph must have a valid CRS attribute in its graph properties
|
|
56
|
+
- MultiGraph/MultiDiGraph inputs will be converted to simple Graph/DiGraph
|
|
57
|
+
"""
|
|
58
|
+
original_crs = gdf_to.crs
|
|
59
|
+
try:
|
|
60
|
+
local_crs = nx_graph.graph["crs"]
|
|
61
|
+
except KeyError as exc:
|
|
62
|
+
raise ValueError("Graph does not have crs attribute") from exc
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
points = gdf_to.copy()
|
|
66
|
+
points.to_crs(local_crs, inplace=True)
|
|
67
|
+
except CRSError as e:
|
|
68
|
+
raise CRSError(f"Graph crs ({local_crs}) has invalid format.") from e
|
|
69
|
+
|
|
70
|
+
nx_graph, reversed_graph = reverse_graph(nx_graph, weight_type)
|
|
71
|
+
|
|
72
|
+
points.geometry = points.representative_point()
|
|
73
|
+
|
|
74
|
+
_, nearest_nodes = get_closest_nodes_from_gdf(points, nx_graph)
|
|
75
|
+
|
|
76
|
+
points["nearest_node"] = nearest_nodes
|
|
77
|
+
|
|
78
|
+
nearest_paths = nx.multi_source_dijkstra_path(
|
|
79
|
+
reversed_graph, nearest_nodes, weight=weight_type, cutoff=weight_value_cutoff
|
|
80
|
+
)
|
|
81
|
+
reachable_nodes = list(nearest_paths.keys())
|
|
82
|
+
graph_points = pd.DataFrame(
|
|
83
|
+
data=[{"node": node, "geometry": Point(data["x"], data["y"])} for node, data in nx_graph.nodes(data=True)]
|
|
84
|
+
).set_index("node")
|
|
85
|
+
nearest_nodes = pd.DataFrame(
|
|
86
|
+
data=[path[0] for path in nearest_paths.values()], index=reachable_nodes, columns=["node_to"]
|
|
87
|
+
)
|
|
88
|
+
graph_nodes_gdf = gpd.GeoDataFrame(
|
|
89
|
+
graph_points.merge(nearest_nodes, left_index=True, right_index=True, how="left"),
|
|
90
|
+
geometry="geometry",
|
|
91
|
+
crs=local_crs,
|
|
92
|
+
)
|
|
93
|
+
graph_nodes_gdf["node_to"] = graph_nodes_gdf["node_to"].fillna("non_reachable")
|
|
94
|
+
voronois = gpd.GeoDataFrame(geometry=graph_nodes_gdf.voronoi_polygons(), crs=local_crs)
|
|
95
|
+
graph_nodes_gdf = graph_nodes_gdf[graph_nodes_gdf["node_to"] != "non_reachable"]
|
|
96
|
+
zone_coverages = voronois.sjoin(graph_nodes_gdf).dissolve(by="node_to").reset_index().drop(columns=["node"])
|
|
97
|
+
zone_coverages = zone_coverages.merge(
|
|
98
|
+
points.drop(columns="geometry"), left_on="node_to", right_on="nearest_node", how="inner"
|
|
99
|
+
).reset_index(drop=True)
|
|
100
|
+
zone_coverages.drop(columns=["node_to", "nearest_node"], inplace=True)
|
|
101
|
+
if zone is None:
|
|
102
|
+
zone = concave_hull(graph_nodes_gdf[~graph_nodes_gdf["node_to"].isna()].union_all(), ratio=0.5)
|
|
103
|
+
else:
|
|
104
|
+
zone = zone.to_crs(local_crs)
|
|
105
|
+
return zone_coverages.clip(zone).to_crs(original_crs)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import geopandas as gpd
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def get_radius_coverage(gdf_from: gpd.GeoDataFrame, radius: float, resolution: int = 32):
|
|
6
|
+
"""
|
|
7
|
+
Calculate radius-based coverage zones using Voronoi polygons.
|
|
8
|
+
|
|
9
|
+
Args:
|
|
10
|
+
gdf_from (gpd.GeoDataFrame):
|
|
11
|
+
Source points for which coverage zones are calculated.
|
|
12
|
+
|
|
13
|
+
radius (float):
|
|
14
|
+
Maximum coverage radius in meters.
|
|
15
|
+
|
|
16
|
+
resolution (int):
|
|
17
|
+
Number of segments used to approximate quarter-circle in buffer (default=32).
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
gpd.GeoDataFrame:
|
|
21
|
+
GeoDataFrame with smoothed coverage zone polygons in the same CRS as original gdf_from.
|
|
22
|
+
|
|
23
|
+
Notes:
|
|
24
|
+
- Automatically converts to local UTM CRS for accurate distance measurements
|
|
25
|
+
- Final zones are slightly contracted then expanded for smoothing effect
|
|
26
|
+
"""
|
|
27
|
+
original_crs = gdf_from.crs
|
|
28
|
+
local_crs = gdf_from.estimate_utm_crs()
|
|
29
|
+
gdf_from = gdf_from.to_crs(local_crs)
|
|
30
|
+
bounds = gdf_from.buffer(radius).union_all()
|
|
31
|
+
coverage_polys = gpd.GeoDataFrame(geometry=gdf_from.voronoi_polygons().clip(bounds, keep_geom_type=True))
|
|
32
|
+
coverage_polys = coverage_polys.sjoin(gdf_from)
|
|
33
|
+
coverage_polys["area"] = coverage_polys.area
|
|
34
|
+
coverage_polys["buffer"] = np.pow(coverage_polys["area"], 1 / 3)
|
|
35
|
+
coverage_polys.geometry = coverage_polys.buffer(-coverage_polys["buffer"], resolution=1, join_style="mitre").buffer(
|
|
36
|
+
coverage_polys["buffer"] * 0.9, resolution=resolution
|
|
37
|
+
)
|
|
38
|
+
coverage_polys.drop(columns=["buffer", "area"], inplace=True)
|
|
39
|
+
return coverage_polys.to_crs(original_crs)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
import geopandas as gpd
|
|
4
|
+
import networkx as nx
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from pyproj.exceptions import CRSError
|
|
8
|
+
from shapely import Point, concave_hull
|
|
9
|
+
|
|
10
|
+
from objectnat.methods.isochrones.isochrone_utils import create_separated_dist_polygons
|
|
11
|
+
from objectnat.methods.utils.graph_utils import get_closest_nodes_from_gdf, reverse_graph
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_stepped_graph_coverage(
|
|
15
|
+
gdf_to: gpd.GeoDataFrame,
|
|
16
|
+
nx_graph: nx.Graph,
|
|
17
|
+
weight_type: Literal["time_min", "length_meter"],
|
|
18
|
+
step_type: Literal["voronoi", "separate"],
|
|
19
|
+
weight_value_cutoff: float = None,
|
|
20
|
+
zone: gpd.GeoDataFrame = None,
|
|
21
|
+
step: float = None,
|
|
22
|
+
):
|
|
23
|
+
"""
|
|
24
|
+
Calculate stepped coverage zones from source points through a graph network using Dijkstra's algorithm
|
|
25
|
+
and Voronoi-based or buffer-based isochrone steps.
|
|
26
|
+
|
|
27
|
+
This function combines graph-based accessibility with stepped isochrone logic. It:
|
|
28
|
+
1. Finds nearest graph nodes for each input point
|
|
29
|
+
2. Computes reachability for increasing weights (e.g. time or distance) in defined steps
|
|
30
|
+
3. Generates Voronoi-based or separate buffer zones around network nodes
|
|
31
|
+
4. Aggregates zones into stepped coverage layers
|
|
32
|
+
5. Optionally clips results to a boundary zone
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
gdf_to (gpd.GeoDataFrame):
|
|
36
|
+
Source points from which stepped coverage is calculated.
|
|
37
|
+
|
|
38
|
+
nx_graph (nx.Graph):
|
|
39
|
+
NetworkX graph representing the transportation network.
|
|
40
|
+
|
|
41
|
+
weight_type:
|
|
42
|
+
Type of edge weight to use for path calculation:
|
|
43
|
+
|
|
44
|
+
- ``"time_min"``: Edge travel time in minutes
|
|
45
|
+
- ``"length_meter"``: Edge length in meters
|
|
46
|
+
|
|
47
|
+
step_type:
|
|
48
|
+
Method for generating stepped zones:
|
|
49
|
+
|
|
50
|
+
- ``"voronoi"``: Stepped zones based on Voronoi polygons around graph nodes
|
|
51
|
+
- ``"separate"``: Independent buffer zones per step
|
|
52
|
+
|
|
53
|
+
weight_value_cutoff (float, optional):
|
|
54
|
+
Maximum weight value (e.g., max travel time or distance) to limit the coverage extent.
|
|
55
|
+
|
|
56
|
+
zone (gpd.GeoDataFrame, optional):
|
|
57
|
+
Optional boundary polygon to clip resulting stepped zones. If None, concave hull of reachable area is used.
|
|
58
|
+
|
|
59
|
+
step (float, optional):
|
|
60
|
+
Step interval for coverage zone construction. Defaults to:
|
|
61
|
+
|
|
62
|
+
- 100 meters for distance-based weight
|
|
63
|
+
- 1 minute for time-based weight
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
gpd.GeoDataFrame:
|
|
67
|
+
GeoDataFrame with polygons representing stepped coverage zones for each input point,
|
|
68
|
+
annotated by step range.
|
|
69
|
+
|
|
70
|
+
Notes:
|
|
71
|
+
- Input graph must have a valid CRS defined.
|
|
72
|
+
- MultiGraph or MultiDiGraph inputs will be simplified to Graph/DiGraph.
|
|
73
|
+
- Designed for accessibility and spatial equity analyses over multimodal networks.
|
|
74
|
+
"""
|
|
75
|
+
if step is None:
|
|
76
|
+
if weight_type == "length_meter":
|
|
77
|
+
step = 100
|
|
78
|
+
else:
|
|
79
|
+
step = 1
|
|
80
|
+
original_crs = gdf_to.crs
|
|
81
|
+
try:
|
|
82
|
+
local_crs = nx_graph.graph["crs"]
|
|
83
|
+
except KeyError as exc:
|
|
84
|
+
raise ValueError("Graph does not have crs attribute") from exc
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
points = gdf_to.copy()
|
|
88
|
+
points.to_crs(local_crs, inplace=True)
|
|
89
|
+
except CRSError as e:
|
|
90
|
+
raise CRSError(f"Graph crs ({local_crs}) has invalid format.") from e
|
|
91
|
+
|
|
92
|
+
nx_graph, reversed_graph = reverse_graph(nx_graph, weight_type)
|
|
93
|
+
|
|
94
|
+
points.geometry = points.representative_point()
|
|
95
|
+
|
|
96
|
+
distances, nearest_nodes = get_closest_nodes_from_gdf(points, nx_graph)
|
|
97
|
+
|
|
98
|
+
points["nearest_node"] = nearest_nodes
|
|
99
|
+
points["distance"] = distances
|
|
100
|
+
|
|
101
|
+
dist = nx.multi_source_dijkstra_path_length(
|
|
102
|
+
reversed_graph, nearest_nodes, weight=weight_type, cutoff=weight_value_cutoff
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
graph_points = pd.DataFrame(
|
|
106
|
+
data=[{"node": node, "geometry": Point(data["x"], data["y"])} for node, data in nx_graph.nodes(data=True)]
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
nearest_nodes = pd.DataFrame.from_dict(dist, orient="index", columns=["dist"]).reset_index()
|
|
110
|
+
|
|
111
|
+
graph_nodes_gdf = gpd.GeoDataFrame(
|
|
112
|
+
graph_points.merge(nearest_nodes, left_on="node", right_on="index", how="left").reset_index(drop=True),
|
|
113
|
+
geometry="geometry",
|
|
114
|
+
crs=local_crs,
|
|
115
|
+
)
|
|
116
|
+
graph_nodes_gdf.drop(columns=["index", "node"], inplace=True)
|
|
117
|
+
if weight_value_cutoff is None:
|
|
118
|
+
weight_value_cutoff = max(nearest_nodes["dist"])
|
|
119
|
+
if step_type == "voronoi":
|
|
120
|
+
graph_nodes_gdf["dist"] = np.minimum(np.ceil(graph_nodes_gdf["dist"] / step) * step, weight_value_cutoff)
|
|
121
|
+
voronois = gpd.GeoDataFrame(geometry=graph_nodes_gdf.voronoi_polygons(), crs=local_crs)
|
|
122
|
+
zone_coverages = voronois.sjoin(graph_nodes_gdf).dissolve(by="dist", as_index=False, dropna=False)
|
|
123
|
+
zone_coverages = zone_coverages[["dist", "geometry"]].explode(ignore_index=True)
|
|
124
|
+
if zone is None:
|
|
125
|
+
zone = concave_hull(graph_nodes_gdf[~graph_nodes_gdf["node_to"].isna()].union_all(), ratio=0.5)
|
|
126
|
+
else:
|
|
127
|
+
zone = zone.to_crs(local_crs)
|
|
128
|
+
zone_coverages = zone_coverages.clip(zone).to_crs(original_crs)
|
|
129
|
+
else: # step_type == 'separate':
|
|
130
|
+
speed = 83.33 # TODO HARDCODED WALK SPEED
|
|
131
|
+
weight_value = weight_value_cutoff
|
|
132
|
+
zone_coverages = create_separated_dist_polygons(graph_nodes_gdf, weight_value, weight_type, step, speed)
|
|
133
|
+
if zone is not None:
|
|
134
|
+
zone = zone.to_crs(local_crs)
|
|
135
|
+
zone_coverages = zone_coverages.clip(zone).to_crs(original_crs)
|
|
136
|
+
return zone_coverages
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .isochrones import get_accessibility_isochrones, get_accessibility_isochrone_stepped
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
import geopandas as gpd
|
|
4
|
+
import networkx as nx
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from pyproj.exceptions import CRSError
|
|
8
|
+
from shapely.ops import polygonize
|
|
9
|
+
|
|
10
|
+
from objectnat import config
|
|
11
|
+
from objectnat.methods.utils.geom_utils import polygons_to_multilinestring
|
|
12
|
+
from objectnat.methods.utils.graph_utils import get_closest_nodes_from_gdf, remove_weakly_connected_nodes
|
|
13
|
+
|
|
14
|
+
logger = config.logger
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _validate_inputs(
|
|
18
|
+
points: gpd.GeoDataFrame, weight_value: float, weight_type: Literal["time_min", "length_meter"], nx_graph: nx.Graph
|
|
19
|
+
) -> tuple[str, str]:
|
|
20
|
+
"""Validate common inputs for accessibility functions."""
|
|
21
|
+
if weight_value <= 0:
|
|
22
|
+
raise ValueError("Weight value must be greater than 0")
|
|
23
|
+
if weight_type not in ["time_min", "length_meter"]:
|
|
24
|
+
raise UserWarning("Weight type should be either 'time_min' or 'length_meter'")
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
local_crs = nx_graph.graph["crs"]
|
|
28
|
+
except KeyError as exc:
|
|
29
|
+
raise ValueError("Graph does not have crs attribute") from exc
|
|
30
|
+
try:
|
|
31
|
+
graph_type = nx_graph.graph["type"]
|
|
32
|
+
except KeyError as exc:
|
|
33
|
+
raise ValueError("Graph does not have type attribute") from exc
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
points.to_crs(local_crs, inplace=True)
|
|
37
|
+
except CRSError as e:
|
|
38
|
+
raise CRSError(f"Graph crs ({local_crs}) has invalid format.") from e
|
|
39
|
+
|
|
40
|
+
return local_crs, graph_type
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _prepare_graph_and_nodes(
|
|
44
|
+
points: gpd.GeoDataFrame, nx_graph: nx.Graph, graph_type: str, weight_type: str, weight_value: float
|
|
45
|
+
) -> tuple[nx.Graph, gpd.GeoDataFrame, pd.DataFrame, float]:
|
|
46
|
+
"""Prepare graph and calculate nearest nodes with distances."""
|
|
47
|
+
nx_graph = remove_weakly_connected_nodes(nx_graph)
|
|
48
|
+
distances, nearest_nodes = get_closest_nodes_from_gdf(points, nx_graph)
|
|
49
|
+
points["nearest_node"] = nearest_nodes
|
|
50
|
+
|
|
51
|
+
dist_nearest = pd.DataFrame(data=distances, index=nearest_nodes, columns=["dist"]).drop_duplicates()
|
|
52
|
+
|
|
53
|
+
# Calculate speed adjustment if needed
|
|
54
|
+
speed = 0
|
|
55
|
+
if graph_type in ["walk", "intermodal"] and weight_type == "time_min":
|
|
56
|
+
try:
|
|
57
|
+
speed = nx_graph.graph["walk_speed"]
|
|
58
|
+
except KeyError:
|
|
59
|
+
logger.warning("There is no walk_speed in graph, set to the default speed - 83.33 m/min")
|
|
60
|
+
speed = 83.33
|
|
61
|
+
dist_nearest = dist_nearest / speed
|
|
62
|
+
elif weight_type == "time_min":
|
|
63
|
+
speed = 20 * 1000 / 60
|
|
64
|
+
dist_nearest = dist_nearest / speed
|
|
65
|
+
|
|
66
|
+
if (dist_nearest > weight_value).all().all():
|
|
67
|
+
raise RuntimeError(
|
|
68
|
+
"The point(s) lie further from the graph than weight_value, it's impossible to "
|
|
69
|
+
"construct isochrones. Check the coordinates of the point(s)/their projection"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
return nx_graph, points, dist_nearest, speed
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _process_pt_data(
|
|
76
|
+
nodes: gpd.GeoDataFrame, edges: gpd.GeoDataFrame, graph_type: str
|
|
77
|
+
) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame] | tuple[None, None]:
|
|
78
|
+
"""Process public transport data if available."""
|
|
79
|
+
if "type" in nodes.columns and "platform" in nodes["type"].unique():
|
|
80
|
+
pt_nodes = nodes[(nodes["type"] != "platform") & (~nodes["type"].isna())]
|
|
81
|
+
if graph_type == "intermodal":
|
|
82
|
+
edges = edges[~edges["type"].isin(["walk", "boarding"])]
|
|
83
|
+
pt_nodes = pt_nodes[["type", "route", "geometry"]]
|
|
84
|
+
edges = edges[["type", "route", "geometry"]]
|
|
85
|
+
return pt_nodes, edges
|
|
86
|
+
return None, None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _calculate_distance_matrix(
|
|
90
|
+
nx_graph: nx.Graph,
|
|
91
|
+
nearest_nodes: np.ndarray,
|
|
92
|
+
weight_type: str,
|
|
93
|
+
weight_value: float,
|
|
94
|
+
dist_nearest: pd.DataFrame,
|
|
95
|
+
) -> tuple[pd.DataFrame, nx.Graph]:
|
|
96
|
+
"""Calculate distance matrix from nearest nodes."""
|
|
97
|
+
|
|
98
|
+
data = {}
|
|
99
|
+
for source in nearest_nodes:
|
|
100
|
+
dist = nx.single_source_dijkstra_path_length(nx_graph, source, weight=weight_type, cutoff=weight_value)
|
|
101
|
+
data.update({source: dist})
|
|
102
|
+
|
|
103
|
+
dist_matrix = pd.DataFrame.from_dict(data, orient="index")
|
|
104
|
+
dist_matrix = dist_matrix.add(dist_nearest.dist, axis=0)
|
|
105
|
+
dist_matrix = dist_matrix.mask(dist_matrix > weight_value, np.nan)
|
|
106
|
+
dist_matrix.dropna(how="all", inplace=True)
|
|
107
|
+
dist_matrix.dropna(how="all", axis=1, inplace=True)
|
|
108
|
+
|
|
109
|
+
subgraph = nx_graph.subgraph(dist_matrix.columns.to_list())
|
|
110
|
+
|
|
111
|
+
return dist_matrix, subgraph
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _create_isochrones_gdf(
|
|
115
|
+
points: gpd.GeoDataFrame,
|
|
116
|
+
results: list,
|
|
117
|
+
dist_matrix: pd.DataFrame,
|
|
118
|
+
local_crs: str,
|
|
119
|
+
weight_type: str,
|
|
120
|
+
weight_value: float,
|
|
121
|
+
) -> gpd.GeoDataFrame:
|
|
122
|
+
"""Create final isochrones GeoDataFrame."""
|
|
123
|
+
isochrones = gpd.GeoDataFrame(geometry=results, index=dist_matrix.index, crs=local_crs)
|
|
124
|
+
isochrones = (
|
|
125
|
+
points.drop(columns="geometry")
|
|
126
|
+
.merge(isochrones, left_on="nearest_node", right_index=True, how="left")
|
|
127
|
+
.drop(columns="nearest_node")
|
|
128
|
+
)
|
|
129
|
+
isochrones = gpd.GeoDataFrame(isochrones, geometry="geometry", crs=local_crs)
|
|
130
|
+
isochrones["weight_type"] = weight_type
|
|
131
|
+
isochrones["weight_value"] = weight_value
|
|
132
|
+
return isochrones
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def create_separated_dist_polygons(
|
|
136
|
+
points: gpd.GeoDataFrame, weight_value, weight_type, step, speed
|
|
137
|
+
) -> gpd.GeoDataFrame:
|
|
138
|
+
points["dist"] = points["dist"].clip(lower=0.1)
|
|
139
|
+
steps = np.arange(0, weight_value + step, step)
|
|
140
|
+
if steps[-1] > weight_value:
|
|
141
|
+
steps[-1] = weight_value # Ensure last step doesn't exceed weight_value
|
|
142
|
+
for i in range(len(steps) - 1):
|
|
143
|
+
min_dist = steps[i]
|
|
144
|
+
max_dist = steps[i + 1]
|
|
145
|
+
nodes_in_step = points["dist"].between(min_dist, max_dist, inclusive="left")
|
|
146
|
+
nodes_in_step = nodes_in_step[nodes_in_step].index
|
|
147
|
+
if not nodes_in_step.empty:
|
|
148
|
+
buffer_size = (max_dist - points.loc[nodes_in_step, "dist"]) * 0.7
|
|
149
|
+
if weight_type == "time_min":
|
|
150
|
+
buffer_size = buffer_size * speed
|
|
151
|
+
points.loc[nodes_in_step, "buffer_size"] = buffer_size
|
|
152
|
+
points.geometry = points.geometry.buffer(points["buffer_size"])
|
|
153
|
+
points["dist"] = np.minimum(np.ceil(points["dist"] / step) * step, weight_value)
|
|
154
|
+
points = points.dissolve(by="dist", as_index=False)
|
|
155
|
+
polygons = gpd.GeoDataFrame(
|
|
156
|
+
geometry=list(polygonize(points.geometry.apply(polygons_to_multilinestring).union_all())),
|
|
157
|
+
crs=points.crs,
|
|
158
|
+
)
|
|
159
|
+
polygons_points = polygons.copy()
|
|
160
|
+
polygons_points.geometry = polygons.representative_point()
|
|
161
|
+
stepped_polygons = polygons_points.sjoin(points, predicate="within").reset_index()
|
|
162
|
+
stepped_polygons = stepped_polygons.groupby("index").agg({"dist": "mean"})
|
|
163
|
+
stepped_polygons["dist"] = np.minimum(np.floor(stepped_polygons["dist"] / step) * step, weight_value)
|
|
164
|
+
stepped_polygons["geometry"] = polygons
|
|
165
|
+
stepped_polygons = gpd.GeoDataFrame(stepped_polygons, geometry="geometry", crs=points.crs).reset_index(drop=True)
|
|
166
|
+
stepped_polygons = stepped_polygons.dissolve(by="dist", as_index=False).explode(ignore_index=True)
|
|
167
|
+
return stepped_polygons
|