sfttoolbox 0.0.0__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.
@@ -0,0 +1,341 @@
1
+ import json
2
+ import os
3
+ from typing import List, Tuple
4
+
5
+ import folium
6
+ import geopandas as gpd
7
+ import numpy as np
8
+ import pandas as pd
9
+ from folium.plugins import MarkerCluster
10
+ from shapely.geometry import Point, Polygon
11
+
12
+ from .isochrone_generator import *
13
+
14
+ __all__ = ["LineString", "Point", "Polygon", "SomersetMap"]
15
+
16
+
17
+ class SomersetMap:
18
+ """
19
+ Class for generating a map of Somerset with various overlays such as isochrones, bus routes, deprivation, etc.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ somerset_boundary_filepath="somerset_geojson_files\somerset_boundary.geojson",
25
+ ) -> None:
26
+ """
27
+ Initialise SomersetMap with base layers and data sources.
28
+
29
+
30
+ Args:
31
+ somerset_boundary_filepath (str, optional): Filepath to the somerset boundary. Defaults to "somerset_geojson_files\somerset_boundary.geojson".
32
+ """
33
+ self.somerset_map = folium.Map(location=(51.1, -3.12), zoom_start=10)
34
+
35
+ self.ig = IsochroneGenerator()
36
+
37
+ self.somerset_boundary = gpd.read_file(somerset_boundary_filepath)
38
+
39
+ self.hospital = {
40
+ "Musgrove Park Hospital": (51.0113, -3.1207),
41
+ "Yeovil Hospital": (50.9448, -2.6343),
42
+ "Bridgwater Community Hospital": (51.14085360901964, -2.974170545072063),
43
+ "Burnham on Sea War Memorial Hospital": (
44
+ 51.238808283995766,
45
+ -2.9939277761197807,
46
+ ),
47
+ "Chard Community Hospital": (50.87498034302077, -2.952198452035544),
48
+ "Crewkerne Community Hospital": (50.88106143909538, -2.798288304583778),
49
+ "Frome Community Hospital": (51.2380413382477, -2.311445023871734),
50
+ "Minehead Community Hospital": (51.19888085156418, -3.462695643764723),
51
+ "Shepton Mallet Community Hospital": (
52
+ 51.1906165919531,
53
+ -2.5629966353081692,
54
+ ),
55
+ "South Petherton Community Hospital": (
56
+ 50.95303541112399,
57
+ -2.7983586716761666,
58
+ ),
59
+ "Wellington Community Hospital": (50.97624187906184, -3.2270782289259015),
60
+ "West Mendip Community Hospital": (51.16024240105559, -2.6988811741334575),
61
+ "Williton Community Hospital": (51.16271743071589, -3.3233721026623186),
62
+ "Wincanton Community Hospital": (51.05876870837557, -2.418038785500917),
63
+ "Somerton Surgery": (51.055774099646946, -2.730676692033103),
64
+ "Victoria Park Health and Wellbeing Hub": (
65
+ 51.13048927483262,
66
+ -3.012210117835418,
67
+ ),
68
+ "Lister House Surgery": (51.04113582737272, -3.313386475267806),
69
+ }
70
+
71
+ def _create_isochrones(
72
+ self,
73
+ selected_centers: List[str],
74
+ travel_time: int,
75
+ filepath: str = "pre_run_isochrones/",
76
+ ) -> dict:
77
+ """
78
+ Generate isochrones for selected centers.
79
+
80
+ Args:
81
+ selected_centers (list[str]): List of selected hospital names.
82
+ travel_time (int): Travel time in minutes.
83
+ filepath (str, optional): Filepath to save isochrones. Defaults to "pre_run_isochrones/".
84
+
85
+ Returns:
86
+ dict: Dictionary of hospital names and corresponding isochrone GeoDataFrames.
87
+ """
88
+ isochrone_dict = {}
89
+
90
+ for hospital_name in selected_centers:
91
+ isochrone_filename = (
92
+ f"{filepath}{hospital_name}_{travel_time}_min_isochrone.geojson"
93
+ )
94
+
95
+ if os.path.isfile(isochrone_filename):
96
+ isochrone_dict[hospital_name] = gpd.read_file(isochrone_filename)
97
+
98
+ else:
99
+ # TODO: Add check that hospital_name is in hospital
100
+ lat, lon = self.hospital[hospital_name]
101
+ isochrone_geom = self.ig.generate_isochrone(
102
+ hospital_name, lat, lon, travel_time, True
103
+ )
104
+ isochrone_dict[hospital_name] = gpd.GeoDataFrame(
105
+ index=[0], crs="epsg:4326", geometry=[isochrone_geom]
106
+ )
107
+
108
+ return isochrone_dict
109
+
110
+ def add_isochrone_and_markers(
111
+ self,
112
+ selected_centers: List[str],
113
+ travel_time: int,
114
+ filepath: str = "pre_run_isochrones/",
115
+ icon_background_colour: str = "lightblue",
116
+ colour: str = "white",
117
+ group_prefix: str = "",
118
+ ) -> None:
119
+ """
120
+ Add isochrones and markers to the map.
121
+
122
+ Args:
123
+ selected_centers (list[str]): List of selected hospital names.
124
+ travel_time (int): Travel time in minutes.
125
+ filepath (str, optional): Filepath to save isochrones. Defaults to "pre_run_isochrones/".
126
+ icon_background_colour (str, optional): Background color for icons. Defaults to 'lightblue'.
127
+ colour (str, optional): Color for isochrone polygons. Defaults to 'white'.
128
+ group_prefix (str, optional): Prefix for feature groups. Defaults to "".
129
+ """
130
+ group_prefix = f"{group_prefix}_" if group_prefix else ""
131
+
132
+ isochrone_group = folium.FeatureGroup(f"{group_prefix}Isochrones").add_to(
133
+ self.somerset_map
134
+ )
135
+ marker_group = folium.FeatureGroup(f"{group_prefix}Markers").add_to(
136
+ self.somerset_map
137
+ )
138
+
139
+ isochrones = self._create_isochrones(selected_centers, travel_time, filepath)
140
+ for hospital_name, isochrone_df in isochrones.items():
141
+
142
+ isochrone_clipped = gpd.clip(isochrone_df, self.somerset_boundary)
143
+ y, x = isochrone_clipped["geometry"].iloc[0].exterior.xy
144
+
145
+ folium.Marker(
146
+ location=self.hospital[hospital_name],
147
+ popup=hospital_name,
148
+ icon=folium.Icon(
149
+ color=icon_background_colour,
150
+ icon_color=colour,
151
+ icon="hospital",
152
+ prefix="fa",
153
+ ),
154
+ ).add_to(marker_group)
155
+ folium.Polygon(
156
+ locations=zip(x, y), color=colour, fill_color=colour, fill=True
157
+ ).add_to(isochrone_group)
158
+
159
+ def add_bus_routes(
160
+ self, bus_routes_filepath: str = "somerset_geojson_files/bus_routes.json"
161
+ ) -> None:
162
+ """
163
+ Add bus routes to the map.
164
+
165
+ Args:
166
+ bus_routes_filepath (str, optional): Filepath to the bus routes. Defaults to "somerset_geojson_files/bus_routes.json".
167
+ """
168
+ bus_routes_group = folium.FeatureGroup("Bus Routes").add_to(self.somerset_map)
169
+
170
+ bus_routes = json.load(open(bus_routes_filepath, "r"))
171
+
172
+ # TODO: All this processing is ridiculous, should fix this in the file..
173
+ # TODO: Use colour to indicate frequency??
174
+ for routes in bus_routes:
175
+ for route_name, route in routes.items():
176
+ if route_name in {"TS1", "TS2", "TS3"}:
177
+ # school busses...
178
+ continue
179
+
180
+ # Plotly allowed nans to break the route, folium does not, this splits the route at the nans
181
+ ind = np.unique(np.where(np.isnan(route))[0])
182
+ split_arrs = np.split(route, ind)
183
+
184
+ # removes the nans
185
+ for i in range(1, len(split_arrs)):
186
+ split_arrs[i] = split_arrs[i][1:]
187
+
188
+ # deletes the arrays that are empty as a result
189
+ empty_arrays = [
190
+ i for i, arr in enumerate(split_arrs) if arr.shape[0] == 0
191
+ ]
192
+ for i in sorted(empty_arrays, reverse=True):
193
+ del split_arrs[i]
194
+
195
+ # Some of the list of arrays only contained nans
196
+ if split_arrs:
197
+ folium.PolyLine(
198
+ split_arrs, tooltip=route_name, color="orange"
199
+ ).add_to(bus_routes_group)
200
+
201
+ def add_deprivation(
202
+ self,
203
+ geo_data: str = "somerset_geojson_files\somerset_lsoa2011.geojson",
204
+ data_filepath: str = "somerset_geojson_files\File_7_-_All_IoD2019_Scores__Ranks__Deciles_and_Population_Denominators_3.csv",
205
+ columns: List[str] = [
206
+ "LSOA code (2011)",
207
+ "Index of Multiple Deprivation (IMD) Decile (where 1 is most deprived 10% of LSOAs)",
208
+ ],
209
+ key_on: str = "properties.LSOA11CD",
210
+ ) -> None:
211
+ """
212
+ Add deprivation data to the map.
213
+
214
+ Args:
215
+ geo_data (str, optional): Filepath to the geographical data. Defaults to "somerset_geojson_files\chloropleth_compatible_somerset_lsoa2011.geojson".
216
+ data_filepath (str, optional): Filepath to the data. Defaults to "somerset_geojson_files\File_7_-_All_IoD2019_Scores__Ranks__Deciles_and_Population_Denominators_3.csv"
217
+ columns (list[tuple[float, float]], optional): columns to use from the data. Defaults to ['LSOA code (2011)', 'Index of Multiple Deprivation (IMD) Decile (where 1 is most deprived 10% of LSOAs)']
218
+ key_on (str, optional): Name of the feature in the geographical data to merge with the first column above. Defaults to properties.LSOA11CD
219
+ """
220
+ self._create_chloropleth(
221
+ geo_data,
222
+ "Deprivation",
223
+ "Deprivation",
224
+ pd.read_csv(data_filepath),
225
+ columns,
226
+ key_on,
227
+ ).add_to(self.somerset_map)
228
+
229
+ def add_population(
230
+ self,
231
+ geo_data: str = "somerset_geojson_files\somerset_lsoa2011.geojson",
232
+ data_filepath: str = "somerset_geojson_files\File_7_-_All_IoD2019_Scores__Ranks__Deciles_and_Population_Denominators_3.csv",
233
+ columns: List[str] = [
234
+ "LSOA code (2011)",
235
+ "Total population: mid 2015 (excluding prisoners)",
236
+ ],
237
+ key_on: str = "properties.LSOA11CD",
238
+ ) -> None:
239
+ """
240
+ Add population data to the map.
241
+
242
+ Args:
243
+ geo_data (str, optional): Filepath to the geographical data. Defaults to "somerset_geojson_files\chloropleth_compatible_somerset_lsoa2011.geojson".
244
+ data_filepath (str, optional): Filepath to the data. Defaults to "somerset_geojson_files\File_7_-_All_IoD2019_Scores__Ranks__Deciles_and_Population_Denominators_3.csv"
245
+ columns (list[tuple[float, float]], optional): columns to use from the data. Defaults to ['LSOA code (2011)', 'Total population: mid 2015 (excluding prisoners)']
246
+ key_on (str, optional): Name of the feature in the geographical data to merge with the first column above. Defaults to properties.LSOA11CD
247
+ """
248
+ self._create_chloropleth(
249
+ geo_data,
250
+ "Population",
251
+ "Population",
252
+ pd.read_csv(data_filepath),
253
+ columns,
254
+ key_on,
255
+ ).add_to(self.somerset_map)
256
+
257
+ def _create_chloropleth(
258
+ self,
259
+ geo_data: str,
260
+ name: str,
261
+ legend_name: str,
262
+ data: str,
263
+ columns: List[str],
264
+ key_on: str = "properties.LSOA11CD",
265
+ fill_color: str = "RdBu",
266
+ bins: int = 10,
267
+ fill_opacity: float = 0.7,
268
+ line_opacity: float = 0.1,
269
+ ) -> folium.Choropleth:
270
+ """
271
+ Creates a choropleth layer for a folium map using the provided geospatial and tabular data.
272
+
273
+ Args:
274
+ geo_data (str): Path to the GeoJSON file or a GeoJSON string containing the geographic boundaries.
275
+ name (str): Name of the layer to be displayed in the map's layer control.
276
+ legend_name (str): Title for the legend displayed on the map.
277
+ data (str): Path to the data file (e.g., CSV) or a DataFrame containing the values to visualise.
278
+ columns (List[str]): A list with two elements: the first is the column with geographic identifiers,
279
+ and the second is the column with the values to visualise.
280
+ key_on (str, optional): The GeoJSON property key to match with the data. Defaults to "properties.LSOA11CD".
281
+ fill_color (str, optional): Colour scheme for the choropleth. Defaults to "RdBu".
282
+ bins (int, optional): Number of bins to divide the data into. Defaults to 10.
283
+ fill_opacity (float, optional): Opacity of the fill colour. Defaults to 0.7.
284
+ line_opacity (float, optional): Opacity of the boundary lines. Defaults to 0.1.
285
+
286
+ Returns:
287
+ folium.Choropleth: A folium Choropleth object that can be added to a folium map.
288
+ """
289
+ return folium.Choropleth(
290
+ geo_data=geo_data,
291
+ name=name,
292
+ data=data,
293
+ columns=columns,
294
+ key_on=key_on,
295
+ fill_color=fill_color,
296
+ bins=bins,
297
+ fill_opacity=fill_opacity,
298
+ line_opacity=line_opacity,
299
+ legend_name=legend_name,
300
+ )
301
+
302
+ def add_somerset_boundary(self) -> None:
303
+ """
304
+ Add Somerset boundary to the map.
305
+ """
306
+ folium.GeoJson(
307
+ self.somerset_boundary.boundary,
308
+ style_function=lambda x: {"color": "brown", "weight": 3},
309
+ name="Somerset Boundary",
310
+ ).add_to(self.somerset_map)
311
+
312
+ def add_patient_coords(
313
+ self, patient_coords: List[Tuple[float, float]], layer_name: str = "patients"
314
+ ) -> None:
315
+ """
316
+ Add patient coordinates to the map.
317
+
318
+ Args:
319
+ patient_coords (list[tuple[float, float]]): List of patient coordinates as tuples of (latitude, longitude).
320
+ """
321
+ marker_cluster = MarkerCluster(name=layer_name).add_to(self.somerset_map)
322
+
323
+ for coord in patient_coords:
324
+ folium.features.Circle(coord, fill=True, fill_opacity=1).add_to(
325
+ marker_cluster
326
+ )
327
+
328
+ def add_layer_control(self):
329
+ """
330
+ Add layer control to the map.
331
+ """
332
+ folium.LayerControl().add_to(self.somerset_map)
333
+
334
+ def save(self, filepath: str) -> None:
335
+ """
336
+ Save the map to a file.
337
+
338
+ Args:
339
+ filepath (str): Filepath to save the map.
340
+ """
341
+ self.somerset_map.save(filepath)
File without changes
@@ -0,0 +1,133 @@
1
+ """
2
+ Isochrone Generation Example – Somerset, UK
3
+
4
+ This example demonstrates how to generate drive-time isochrones using OpenStreetMap data and the IsochroneGenerator
5
+ class from `sfttoolbox`. The script performs spatial analysis to compute areas reachable by car within a set travel
6
+ time from hospitals in Somerset and Dorset counties.
7
+
8
+ The main tasks covered in this example include:
9
+
10
+ 1. Loading road network graphs for:
11
+ - Yeovil (centered at lat=50.9448, lon=-2.6343, 15-mile radius)
12
+ - Taunton (centered at lat=51.0113, lon=-3.1207, 15-mile radius)
13
+
14
+ 2. Retrieving and storing the administrative boundaries of:
15
+ - Somerset, UK
16
+ - Dorset, UK
17
+
18
+ 3. Generating 10-minute drive-time isochrone polygons from:
19
+ - Musgrove Park Hospital (Taunton)
20
+ - Yeovil Hospital (Yeovil)
21
+
22
+ 4. Computing:
23
+ - Shortest path routes from Musgrove Park Hospital to isochrone boundary points
24
+ - The full road network within the 10-minute isochrone from Yeovil Hospital
25
+
26
+ 5. Saving all results to:
27
+ - A single GeoJSON file for visualisation
28
+ - HTML map for interactive exploration
29
+ - GraphML files (optional, via `save_graph`) for network analysis
30
+
31
+ Dependencies:
32
+ - geopandas
33
+ - osmnx
34
+ - networkx
35
+ - alphashape
36
+ - shapely
37
+ - folium
38
+
39
+ Usage:
40
+ 1. Run this script using Python:
41
+ python example1.py
42
+
43
+ 2. Open `isochrone_map.html` in your browser to view the interactive map.
44
+
45
+ This example is useful for demonstrating how to apply spatial network analysis to healthcare accessibility or
46
+ transport planning problems using open data and Python tooling.
47
+ """
48
+
49
+ import json
50
+
51
+ import folium
52
+
53
+ from sfttoolbox.mapping import IsochroneGenerator
54
+
55
+ # Initialise the generator
56
+ iso_generator = IsochroneGenerator()
57
+
58
+ # Load road networks for specific locations
59
+ iso_generator.load_graph(
60
+ "Yeovil", lat=50.9448, lon=-2.6343, distance=24140
61
+ ) # 15 miles, default distance is 40 miles
62
+ iso_generator.load_graph("Taunton", lat=51.0113, lon=-3.1207, distance=24140)
63
+
64
+ # Store Somerset's administrative boundary
65
+ iso_generator.generate_boundary("Somerset, UK")
66
+
67
+ # Store Dorset's administrative boundary
68
+ iso_generator.generate_boundary("Dorset, UK")
69
+
70
+ # Generate 10-minute drive-time isochrones
71
+ iso_generator.generate_isochrone(
72
+ place_name="Taunton",
73
+ isochrone_name="Musgrove Park Hospital",
74
+ lat=51.0113,
75
+ lon=-3.1207,
76
+ drive_time=10,
77
+ ) # 10 minutes
78
+ iso_generator.generate_isochrone(
79
+ place_name="Yeovil",
80
+ isochrone_name="Yeovil Hospital",
81
+ lat=50.9448,
82
+ lon=-2.6343,
83
+ drive_time=10,
84
+ )
85
+
86
+ # Compute shortest paths and full road network within isochrones
87
+ iso_generator.generate_shortest_paths("Musgrove Park Hospital")
88
+ iso_generator.convert_road_network_to_gdf("Yeovil Hospital")
89
+
90
+ # Save results
91
+ iso_generator.save_all_data("new_isochrone_data.geojson")
92
+
93
+ # Load GeoJSON data and initialise map
94
+ with open("new_isochrone_data.geojson") as f:
95
+ geojson_data = json.load(f)
96
+
97
+ first_feature = geojson_data["features"][0]
98
+ center_lat, center_lon = (
99
+ first_feature["geometry"]["coordinates"][0][0][1],
100
+ first_feature["geometry"]["coordinates"][0][0][0],
101
+ )
102
+ m = folium.Map(location=[center_lat, center_lon], zoom_start=9)
103
+
104
+ # Plot each feature
105
+ for index, feature in enumerate(geojson_data["features"]):
106
+ props, geometry = feature.get("properties", {}), feature["geometry"]
107
+ feature_type = props.get("type", "unknown")
108
+ name = props.get("name")
109
+ color = "red" if feature_type == "isochrone" else "black"
110
+
111
+ fg = folium.FeatureGroup(name=name, show=True)
112
+
113
+ folium.GeoJson(
114
+ feature,
115
+ style_function=lambda f, col=color: {
116
+ "fillColor": col,
117
+ "color": col,
118
+ "weight": 2,
119
+ "fillOpacity": 0.1,
120
+ },
121
+ ).add_to(fg)
122
+
123
+ if feature_type == "isochrone":
124
+ folium.Marker(
125
+ [props["lat"], props["lon"]], icon=folium.Icon(icon="hospital", prefix="fa")
126
+ ).add_to(fg)
127
+
128
+ fg.add_to(m)
129
+
130
+ # Add Layer Control and save the map
131
+ folium.LayerControl(collapsed=False).add_to(m)
132
+
133
+ m.save("isochrone_map.html")
@@ -0,0 +1,35 @@
1
+ import os
2
+ import shutil
3
+ import urllib.request
4
+ import zipfile
5
+
6
+ from sfttoolbox import mapping
7
+
8
+ # Download the relevant geojson files and unzip them.
9
+ if not os.path.exists("somerset_geojson_files"):
10
+ print("somerset_geojson_files folder not found, downloading.")
11
+ filepath, headers = urllib.request.urlretrieve(
12
+ "https://github.com/Somerset-NHS-FT-DS-Improvement/somerset_geojson_files/archive/refs/heads/main.zip"
13
+ )
14
+
15
+ print("unzipping somerset_geojson_files")
16
+ with zipfile.ZipFile(filepath, "r") as zip_ref:
17
+ zip_ref.extractall(".")
18
+
19
+ print("renaming somerset_geojson_files-main to somerset_geojson_files")
20
+ shutil.move("somerset_geojson_files-main", "somerset_geojson_files")
21
+
22
+ print("creating the map!")
23
+ # Instantiate the map
24
+ sm = mapping.SomersetMap()
25
+
26
+ sm.add_deprivation()
27
+ sm.add_bus_routes()
28
+ sm.add_somerset_boundary()
29
+
30
+ # Allow users to switch between layers
31
+ sm.add_layer_control()
32
+
33
+ # Other functions include add_population or _create_chloropleth can be used to generate a chloropleth layer that can then be added.
34
+
35
+ sm.save("map.html")