-
Notifications
You must be signed in to change notification settings - Fork 3
/
gisruk.qmd
1255 lines (1035 loc) · 51.7 KB
/
gisruk.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
conference: GISRUK 2024
title: Reproducible methods for network simplification for data visualisation and transport planning
author:
- name: Robin Lovelace
affiliation: Leeds Institute for Transport Studies, University of Leeds, UK
orcid: 0000-0001-5679-6536
- name: Zhao Wang
affiliation: Leeds Institute for Transport Studies, University of Leeds, UK
orcid: 0000-0002-4054-0533
- name: Will Deakin
affiliation: Digital, Data and Technology Services, Network Rail, UK
orcid: 0009-0008-5656-4469
- name: Josiah Parry
affiliation: Environmental Systems Research Institute (Esri), Redlands, CA, USA
orcid: 0000-0001-9910-865X
abstract: |
Route network datasets, crucial to transport models, have grown complex, leading to visualization issues and potential misinterpretations. We address this by presenting two methods for simplifying these datasets: image skeletonization and Voronoi diagram-centreline identification. We have developed two packages, the 'parenx' Python package (available on pip) and the 'rnetmatch' R package (available on GitHub) to implement these methods. The approach has applications in transportation, demonstrated by their use in the publicly available Network Planning Tool funded by Transport for Scotland.
keywords: [network simplification, transport planning, urban analytics, geocomputation, reproducible research]
execute:
echo: false
message: false
warning: false
# eval: false
format:
gisruk-pdf:
keep-tex: true
bibliography: bibliography.bib
---
````{=html}
<!--
# Introduction to guidelines {#sec-introduction}
The purpose of providing this template is to standardise the format of the abstracts submitted to GISRUK 2023. These notes are based on author guidelines previously produced for the GISRUK conference series which in turn were based on other guidelines.
The pages should have margins of 2.5 cm all round. The base font should be Times New Roman 11pt, or closest equivalent and text should be single spaced. Each section of the paper should be numbered. Section headings should be left-justified and given in bold type. The title should be 16pt and the authors 14pt. The first line of each paragraph in each section should NOT be indented.
## Sub-sections {#sec-subsections}
Sub-sections should also be numbered as shown here. The sub-section heading should be left-justified and given in bold type (11pt).
# Figures, Tables and Equations {#sec-fig-tab-eq}
Tables should be as below (or as close as possible) and should be referenced as @tbl-conferences in the text.
| Year | Host |
|-----:|--------------------------------------|
| 2015 | University of Leeds |
| 2016 | University of Greenwich |
| 2017 | University of Manchester |
| 2018 | University of Leicester |
| 2019 | University of Newcastle |
| 2020 | UCL & Birkbeck, University of London |
| 2021 | Cardiff University |
| 2022 | University of Liverpool |
| 2023 | University of Glasgow |
: GISRUK Conferences {#tbl-conferences}
Equations should be centred on the page and numbered consecutively in the right-hand margin, as below. They should be referred to in the text as @eq-l-function.
$$
L=\sqrt{\frac{K(d)}{\pi}}-d
$$ {#eq-l-function}
Figures should be presented as part of the paper and should be referred to as @fig-l-function in the text.
```{r}
#| label: fig-l-function
#| fig-cap: Example of L-function plot.
#| echo: false
#| message: FALSE
#| warning: FALSE
#| results: 'hide'
#| fig.height: 5
#| fig.width: 5
#| fig-pos: tbh
library(spatstat)
data.frame(
x = c(
rnorm(100, mean = 10, sd = 5),
runif(400, min = 0, max = 100)
),
y = c(
rnorm(100, mean = 10, sd = 5),
runif(400, min = 0, max = 100)
)
) |>
as.matrix() |>
as.ppp(c(0,100,0,100)) |>
envelope(Lest, correction="border") |>
plot(main = "Random points plus cluster (with sd = 5)")
```
# References and Citations {#sec-cite}
A list of references cited should be provided at the end of the paper using the Harvard format as shown below. Citations of these within the text should be given as follows: papers such as an interesting one by @doi:10.1080/13658810600661607 and also interesting books [@cargill2021writing].
# File format and length {#sec-file-format-len}
Abstracts should be submitted in unrestricted pdf format. Authors are requested to keep to the word limit of 1500 words. The word limit includes the main body of the abstract and everything within (including captions etc.,) and the references. Not included in the word count is the title, author list, date, summary, keywords and author biographies
# Acknowledgements {.appendix .unnumbered}
Acknowledgement should be made of any funding bodies who have supported the work reported in the paper, of those who have given permission for their work to be reproduced or of individuals whose particular assistance is due recognition. Acknowledge data providers here where appropriate.
# Biographies {.appendix .unnumbered}
All contributing authors should include a biography of no more than 50 words each outlining their career stage and research interests. -->
````
```{r}
#| name: python-setup
#| include: false
requirements_txt = readLines("requirements.txt")
# Check if Python is installed:
if (!requireNamespace("reticulate")) {
install.packages("reticulate")
}
reticulate::install_python()
# Install Python dependencies with reticulate:
reticulate::py_install(requirements_txt, pip = TRUE)
```
```{r}
#| name: r-setup
library(sf)
library(tmap)
library(dplyr)
library(ggplot2)
library(stplanr)
tmap_mode("plot")
rnet_x = sf::read_sf("https://github.com/ropensci/stplanr/releases/download/v1.0.2/rnet_x_ed.geojson")
rnet_y = sf::read_sf("https://github.com/ropensci/stplanr/releases/download/v1.0.2/rnet_y_ed.geojson")
```
# Introduction
Datasets representing route networks are important in every stage of modern data-driven transport planning.
Geographically, the same physical network can be represented in many different ways, ranging from simple 'centreline' representations to complex representations with multiple parallel ways.
For some use cases, including strategic network planning, it is important to have a simple representation of the network.
Vector geometry simplification methods include Douglas-Peucker and Visvalingam-Whyatt algorithms [@de2014efficient].
These methods reduce the number of vertices in a line or polygon features, but do not remove parallel ways.
More sophisticated methods to help simplify complex networks include the automatic detection of 'face artifacts' [@fleischmann] and removal of 'slivers' to generate simplified representations of 'street blocks' [@grippa2018].
However, these methods tend to be 'all or nothing' and do not provide flexibility in terms of the level of simplification or which features are removed.
We note the simplification and interpolation for with linear (one-dimensional) geometries is less mature than Polygon or MultiPolygon (two-dimensional) geometry.
For example robust implementation for the areal interpolation of intensive and extensive variables are available in `R` areal-weighted-interpolation package[@prener2019] or in the `python` PySAL Tobler library [@knaap2023].
The aim of this paper is to present new ways to simplify transport networks, with implementations in open source software for reproducible research.
The code underlying the results presented in this paper are available from the following repositories:
- The [`nptscot/networkmerge`](https://github.com/nptscot/networkmerge) repository contains the reproducible paper.
- The `parenx` Python for image skeletonization and Voronoi diagram-centreline identification is available on PyPI in the GitHub repo [`anisotropi4/parenx`](https://github.com/anisotropi4/parenx).
- The `rnetmatch` R package for network simplification is available on GitHub in the repo [`nptscot/rnetmatch`](https://github.com/nptscot/rnetmatch).
```{=html}
<!-- @sec-problem outlines the problem of complex route networks.
@sec-data describes the input datasets.
@sec-methods presents methods for route network simplification alongside results based on the example datasets.
In @sec-discussion we discuss the results and outline future work. -->
```
```{=html}
<!-- Much research has focussed on generating and modelling transport network datasets.
This is unsurprising given the importance of transport networks as inputs and outputs of transport models.
Much has been written about network 'cleaning' and simplification as a pre-processing step in transport modelling. -->
```
<!-- Todo: add papers on network cleaning and simplification. -->
<!-- However, there has been relatively little research into transport network visualisation, despite the importance of visualisation to enable more people to understand transport models, for informing policies and prioritising investment in transport planning. -->
# Problem definition {#sec-problem}
@morgan2020 presented methods for combining multiple overlapping routes into a single route network with non-overlapping linestrings for visualisation, implemented in the function `overline()` in the R package `stplanr`.
The approach has been used to visualise large transport networks, informing investment decisions in transport planning internationally.
However, the 'overline' approach does not merge parallel ways that are part of the same corridor, resulting in outputs that are difficult to interpret, as shown in @fig-pct from the Propensity to Cycle Tool for England (PCT), with segment values representing daily commuter cycling potential flows [@lovelace2017].
The left panel shows Otley Road with a flow value of 818 (@fig-otley-road).
The right panel, by contrast, shows three parallel ways parallel to Armley Road with flow values of 515 (shown), 288 and 47 (values not shown) (@fig-armley-road).
Although this section of Armley road has a higher cycling potential than the section of Otley Road shown (515 + 288 + 47 \> 818), this is not clear from the visualisation.
::: {#fig-pct layout-ncol="2"}
![](images/otley-road-narrow.png){#fig-otley-road}
![](images/armley-road-narrow.png){#fig-armley-road}
Illustration of issues associated with route network-level results containing multiple parallel ways on the same corridor: it is not clear from the visualisation that the corridor shown in the right hand figure has greater flow than the corridor shown in the left.
Source: open access Propensity to Cycle Tool results available at www.pct.bike.
:::
<!-- # Data {#sec-data} -->
```{r}
rnet_otley = sf::read_sf("./data/rnet_otley.geojson")
rnet_armley = sf::read_sf("./data/rnet_armley.geojson")
```
# Methods {#sec-methods}
The key contributions of the paper are the novel methods of image skeletonization[@scikit2014; @zha1984; @lee1994], presented in @sec-simplification-via-skeletonization, and simplification with Voronoi diagrams to identify central lines, covered in @sec-simplification-via-voronoi-polygons.
```{=html}
<!-- TODO: shouldn't the following topics be stand-alone subsections rather than existing within the skeletonization section?
Additionally, the section tackles challenges associated with knots at intersections, offering solutions for their removal to simplify the network's appearance.
The concept of a primal network that represents a high level of simplification is explored as well. -->
```
```{=html}
<!-- ## Topology-preserving simplification {#sec-topology-preserving-simplification}
Topology-preserving simplification reduces the number of vertices in a linestring while preserving the topology of the network.
As shown in top panel of @fig-topology-preserving, topology-preserving simplication *can* reduce the number of edges, but fails to merge parallel lines in complex geometries, as shown in the the bottom panel in @fig-topology-preserving. -->
```
<!-- ::: {#fig-topology-preserving layout-ncol="1"} -->
```{r}
#| include: false
input = sf::read_sf('data/rnet_otley.geojson')
input_projected = sf::st_transform(input, "EPSG:27700")
simplification_levels = c(1, 0.5, 0.1, 0.001)
# ordered factor of simplification levels:
simplification_df = data.frame(
id = as.character(1:length(simplification_levels)),
simp_factor = simplification_levels,
keep = paste0("Keep: ", round(as.numeric(simplification_levels) * 100, 2), "%")
)
simplification_df$keep = ordered(simplification_df$keep, levels = simplification_df$keep)
smplfy = function(x_list, keep) {
x_list = lapply(
keep,
function(x) {
res = rmapshaper::ms_simplify(x_list, keep_shapes = TRUE, keep = x)
res$id = x
res
}
)
do.call(rbind, x_list)
}
if (!file.exists("data/input_simplified_otley.geojson")) {
input_simplified = smplfy(input_projected, simplification_levels)
sf::write_sf(input_simplified, "data/input_simplified_otley.geojson", delete_dsn = TRUE)
} else {
input_simplified = sf::read_sf('data/input_simplified_otley.geojson')
}
input_simplified = left_join(
input_simplified,
simplification_df,
by = join_by(id == simp_factor)
)
m_otley = tm_shape(input_simplified, bbox = tmaptools::bb(input_simplified, 1.1)) +
tm_lines() +
tm_facets(by = "keep", free.coords = TRUE)
# Same for Armley:
input = sf::read_sf('data/rnet_armley.geojson')
input_projected = sf::st_transform(input, "EPSG:27700")
if (!file.exists("data/input_simplified_armley.geojson")) {
input_simplified = smplfy(input_projected, simplification_levels)
sf::write_sf(input_simplified, "data/input_simplified_armley.geojson", delete_dsn = TRUE)
} else {
input_simplified = sf::read_sf('data/input_simplified_armley.geojson')
}
input_simplified = left_join(
input_simplified,
simplification_df,
by = join_by(id == simp_factor)
)
m_armley = tm_shape(input_simplified, bbox = tmaptools::bb(input_simplified, 1.1)) +
tm_lines() +
tm_facets(by = "keep", free.coords = TRUE)
# m_otley
tmap_arrange(m_otley, m_armley)
```
```{=html}
<!-- Illustration of topology-preserving simplification, using the `mapshaper` JavaScript package.
The % values represent the "percentage of removable points to retain" argument values used in the simplification process.
::: -->
```
## Simplification via skeletonization {#sec-simplification-via-skeletonization}
<!-- ### Create a projected combined buffered geometry: -->
```{python}
#| name: python-setup-packages
#| include: false
from functools import partial
from shapely import box
from shapely.ops import voronoi_diagram, split
from shapely import box, line_interpolate_point, snap
from shapely.ops import voronoi_diagram
import geopandas as gp
import matplotlib.pyplot as plt
from shapely import get_coordinates, line_merge, set_precision, unary_union
from shapely.geometry import MultiPoint,MultiLineString,LineString,Point
import pandas as pd
import numpy as np
```
```{python}
#| include: false
plt.rcParams["figure.figsize"] = (12, 12)
def get_geometry_buffer(this_gf, radius=8.0):
"""get_geometry_buffer: return radius buffered GeoDataFrame
args:
this_gf: GeoDataFrame to
radius: (default value = 8.0)
returns:
buffered GeoSeries geometry
"""
r = gp.GeoSeries(this_gf, crs=CRS).buffer(radius, join_style="round", cap_style="round")
union = unary_union(r)
try:
r = gp.GeoSeries(union.geoms, crs=CRS)
except AttributeError:
r = gp.GeoSeries(union, crs=CRS)
return r
CRS = "EPSG:27700"
buffer_size = 8.0
radius = buffer_size
def get_split(line, point, separation=1.0e-6):
return list(split(snap(line, point, separation), point).geoms)
def combine_line(line):
"""combine_line: return LineString GeoSeries combining lines with intersecting endpoints
args:
line: mixed LineString GeoSeries
returns:
join LineString GeoSeries
"""
r = MultiLineString(line.values)
return gp.GeoSeries(line_merge(r).geoms, crs=CRS)
EMPTY = LineString([])
def split_ends(line, offset):
if line.length <= 2.0 * offset:
return line, EMPTY, EMPTY
p = line_interpolate_point(line, offset)
head, centre = get_split(line, p)
p = line_interpolate_point(centre, -offset)
centre, tail = get_split(centre, p)
return head, centre, tail
set_precision_pointone = partial(set_precision, grid_size=0.1)
base_otley = gp.read_file("./data/rnet_otley.geojson").to_crs(CRS)
base_otley["geometry"] = base_otley["geometry"].map(set_precision_pointone)
base_otley = combine_line(base_otley["geometry"]).to_frame("geometry")
otley_geometry = get_geometry_buffer(base_otley["geometry"], radius=buffer_size)
# Same for Armley:
base_armley = gp.read_file("./data/rnet_armley.geojson").to_crs(CRS)
base_armley["geometry"] = base_armley["geometry"].map(set_precision_pointone)
base_armley = combine_line(base_armley["geometry"]).to_frame("geometry")
armley_geometry = get_geometry_buffer(base_armley["geometry"], radius=buffer_size)
```
```{python}
split_end = partial(split_ends, offset=np.sqrt(1.5) * radius)
otley_split = pd.DataFrame(base_otley["geometry"].map(split_end).to_list(), columns=["head", "centre", "tail"])
armley_split = pd.DataFrame(base_armley["geometry"].map(split_end).to_list(), columns=["head", "centre", "tail"])
```
<!-- ::: {#fig-split-ends layout-ncol="2"} -->
```{python}
#| include: false
## overlapping
otley_centre = gp.GeoSeries(otley_split["centre"], crs=CRS)
otley_centre = gp.GeoSeries(otley_centre, crs=CRS).buffer(radius, 0, join_style="round", cap_style="round")
combined_otley = gp.GeoSeries(unary_union(otley_centre.values).geoms, crs=CRS)
combined_otley.plot()
```
```{python}
#| include: false
## overlapping
armley_centre = gp.GeoSeries(armley_split["centre"], crs=CRS)
armley_centre = gp.GeoSeries(armley_centre, crs=CRS).buffer(radius, 0, join_style="round", cap_style="round")
combined_armley = gp.GeoSeries(unary_union(armley_centre.values).geoms, crs=CRS)
combined_armley.plot()
```
```{python}
#| include: false
i, j = base_otley.sindex.query(combined_otley, predicate="intersects")
base_otley["class"] = -1
base_otley.loc[j, "class"] = combined_otley.index[i]
count = base_otley.groupby("class").count()
base_otley = base_otley.join(count["geometry"].rename("count"), on="class")
ix = base_otley["class"] == -1
base_otley.loc[ix, "count"] = 0
i, j = base_armley.sindex.query(combined_armley, predicate="intersects")
base_armley["class"] = -1
base_armley.loc[j, "class"] = combined_armley.index[i]
count = base_armley.groupby("class").count()
base_armley = base_armley.join(count["geometry"].rename("count"), on="class")
ix = base_armley["class"] == -1
base_armley.loc[ix, "count"] = 0
```
```{=html}
<!-- @fig-otley-armley-classes shows the segmented buffer geometries of the Otley Road (left) and Armley Road (right) networks.
It effectively highlights the contrast between the more intricate and the simpler sections within these networks. -->
```
```{python}
#| include: false
ix = base_otley["count"].isin([0, 1])
p = base_otley.loc[~ix, "geometry"].copy()
p = p.buffer(radius, 512, join_style="round", cap_style="round")
try:
p = gp.GeoSeries(list(unary_union(p.values).geoms), crs=CRS)
except AttributeError:
p = gp.GeoSeries(unary_union(p.values), crs=CRS)
q = base_otley.loc[ix, "geometry"].buffer(0.612, 64, join_style="mitre", cap_style="round")
otley_segment = pd.concat([p, q])
try:
otley_segment = gp.GeoSeries(list(unary_union(otley_segment.values).geoms), crs=CRS)
except AttributeError:
otley_segment = gp.GeoSeries(unary_union(otley_segment.values), crs=CRS)
otley_segment.plot()
```
```{python}
#| include: false
ix = base_armley["count"].isin([0, 1])
p = base_armley.loc[~ix, "geometry"].copy()
p = p.buffer(radius, 512, join_style="round", cap_style="round")
try:
p = gp.GeoSeries(list(unary_union(p.values).geoms), crs=CRS)
except AttributeError:
p = gp.GeoSeries(unary_union(p.values), crs=CRS)
q = base_armley.loc[ix, "geometry"].buffer(0.612, 64, join_style="mitre", cap_style="round")
armley_segment = pd.concat([p, q])
try:
armley_segment = gp.GeoSeries(list(unary_union(armley_geometry.values).geoms), crs=CRS)
except AttributeError:
armley_segment = gp.GeoSeries(unary_union(armley_segment.values), crs=CRS)
armley_segment.plot()
```
<!-- ### Skeletonization -->
The skeletonization approach is based on the idea of creating a buffer around the network and then skeletonizing the buffer.
The buffered lines of the network are first transformed into a raster image.
Subsequently, this raster image is processed through a thinning algorithm to produce a skeletal representation of the original network.
```{=html}
<!-- This skeletal structure preserves the overall extent and connectivity of the initial network, with a central line that closely follows the contours of the combined buffered area.
To correlate the points in the buffered geometry with their respective positions in the raster image, we implement an affine transformation.
This transformation is scaled to ensure that the projected coordinate geometry of the network aligns accurately with the corresponding dimensions of the scaled raster image.
Through this process, we maintain the spatial integrity and relational positioning of the network elements within the simplified raster format. -->
```
```{python}
#| include: false
import numpy as np
import pandas as pd
import rasterio as rio
import rasterio.features as rif
def get_pxsize(bound, scale=1.0):
"""get_pxsize: calculates scaled image size in px
bound: boundary corner points
scale: scaling factor (default = 1.0)
returns:
size in px
"""
r = np.diff(bound.reshape(-1, 2), axis=0)
r = np.ceil(r.reshape(-1))
return (r[[1, 0]] * scale).astype(int)
def get_affine_transform(this_gf, scale=1.0):
"""get_affine_transform: return affine transformations matrices, and scaled image size
from GeoPandas boundary size
this_gf: GeoPanda
scale: (default = 1.0)
returns:
rasterio and shapely affine tranformation matrices, and image size in px
"""
TRANSFORM_ONE = np.asarray([0.0, 1.0, -1.0, 0.0, 1.0, 1.0])
bound = this_gf.total_bounds
s = TRANSFORM_ONE / scale
s[[4, 5]] = bound[[0, 3]]
r = s[[1, 0, 4, 3, 2, 5]]
r = rio.Affine(*r)
return r, s, get_pxsize(bound, scale)
r_matrix_otley, s_matrix_otley, out_shape_otley = get_affine_transform(otley_geometry, scale=2.0)
# For Armle
r_matrix_armley, s_matrix_armley, out_shape_armley = get_affine_transform(armley_geometry, scale=2.0)
```
```{=html}
<!-- ### Affine transforms
The affine transformations for Rasterio and Shapely are demonstrated with a scaling factor of 2.0.
The Rasterio transform applies a scale and translation in a specific order, while the Shapely transform follows a different order for scaling and rotation, as illustrated in Table @tbl-panel. -->
```
```{python}
#| include: false
from IPython.display import display, Markdown
def display_matrix(matrix, header):
r = matrix.to_markdown(index=False, headers=header)
display(r)
or_matrix_otley = pd.DataFrame(np.asarray(r_matrix_otley).reshape(-1, 3))
os_matrix_otley = pd.DataFrame(np.asarray(s_matrix_otley).reshape(3, -1).T)
or_matrix_armley = pd.DataFrame(np.asarray(r_matrix_armley).reshape(-1, 3))
os_matrix_armley = pd.DataFrame(np.asarray(s_matrix_armley).reshape(3, -1).T)
```
```{python}
import warnings
from skimage.morphology import remove_small_holes, skeletonize
from shapely.affinity import affine_transform
from shapely.geometry import Point
import rasterio.plot as rip
```
```{python}
#| include: false
otley_im = rif.rasterize(otley_segment.values, transform=r_matrix_otley, out_shape=out_shape_otley)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
otley_im = remove_small_holes(otley_im, 20).astype(np.uint8)
rip.show(otley_im, cmap="Greys", title="buffer geometry")
```
```{python}
#| include: false
armley_im = rif.rasterize(armley_segment.values, transform=r_matrix_armley, out_shape=out_shape_otley)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
armley_im = remove_small_holes(armley_im, 20).astype(np.uint8)
rip.show(armley_im, cmap="Greys", title="buffer geometry")
```
```{=html}
<!-- The image undergoes a thinning process, yielding a skeletal raster image as the result.
This skeletonized image effectively captures the essential structure and layout of the original network, as illustrated in @fig-thin-skeleton. -->
```
```{python}
#| include: false
otley_skeleton = skeletonize(otley_im).astype(np.uint8)
rip.show(otley_skeleton, cmap="Greys", title="skeleton geometry")
otley_p = np.stack(np.where(otley_skeleton >= 1))
otley_point = gp.GeoSeries(map(Point, otley_p.T), crs=CRS)
```
```{python}
#| include: false
armley_skeleton = skeletonize(armley_im).astype(np.uint8)
rip.show(armley_skeleton, cmap="Greys", title="skeleton geometry")
armley_p = np.stack(np.where(armley_skeleton >= 1))
armley_point = gp.GeoSeries(map(Point, armley_p.T), crs=CRS)
```
The rasterized skeletal image is then converted back into point geometry, completing the vector-to-raster-to-vector geometry transformation process, as illustrated in @fig-skeleton-line.
<!-- Figure commented out as not necessary and similar to the subsequent figure: -->
<!-- ::: {#fig-skeleton-vector layout-ncol="2"} -->
```{python}
shapely_transform = partial(affine_transform, matrix=s_matrix_otley)
otley_transform = otley_point.map(shapely_transform).map(set_precision_pointone)
# otley_transform.plot(edgecolor="black", color="blue").grid()
# plt.show()
```
```{python}
armley_transform = armley_point.map(shapely_transform).map(set_precision_pointone)
# armley_transform.plot(edgecolor="black", color="blue").grid()
# plt.show()
```
```{python}
from shapely import get_coordinates
from shapely.geometry import LineString, MultiLineString
def get_raster_line_with_knots(point):
"""get_raster_line_with_knots: return LineString GeoSeries from 1px line points with knots
args:
point: 1px point GeoSeries array with knots
returns:
1px line LineString GeoSeries with knots removed
"""
square = point.buffer(1, cap_style="square", mitre_limit=1)
ix = point.sindex.query(square, predicate="covers").T
ix = np.sort(ix)
s = pd.DataFrame(ix).drop_duplicates().reset_index(drop=True)
s = s.loc[np.where(s[0] != s[1])]
s = np.stack([point[s[0].values], point[s[1].values]]).T
r = gp.GeoSeries(map(LineString, s), crs=CRS)
edge, node = get_source_target(combine_line(r).to_frame("geometry"))
return combine_line(edge["geometry"])
def get_end(geometry):
"""get_end: return numpy array of geometry LineString end-points
args:
geometry: geometry LineString
returns:
end-point numpy arrays
"""
r = get_coordinates(geometry)
return np.vstack((r[0, :], r[-1, :]))
def get_source_target(line):
"""get_source_target: return edge and node GeoDataFrames from LineString with unique
node Point and edge source and target
args:
line: LineString GeoDataFrame
returns:
edge, node: GeoDataFrames
"""
edge = line.copy()
r = edge["geometry"].map(get_end)
r = np.stack(r)
node = gp.GeoSeries(map(Point, r.reshape(-1, 2)), crs=CRS).to_frame("geometry")
count = node.groupby("geometry").size().rename("count")
node = node.drop_duplicates("geometry").set_index("geometry", drop=False)
node = node.join(count).reset_index(drop=True).reset_index(names="node")
ix = node.set_index("geometry")["node"]
edge = edge.reset_index(names="edge")
edge["source"] = ix.loc[map(Point, r[:, 0])].values
edge["target"] = ix.loc[map(Point, r[:, 1])].values
return edge, node
def combine_line(line):
"""combine_line: return LineString GeoSeries combining lines with intersecting endpoints
args:
line: mixed LineString GeoSeries
returns:
join LineString GeoSeries
"""
r = MultiLineString(line.values)
return gp.GeoSeries(line_merge(r).geoms, crs=CRS)
otley_line = get_raster_line_with_knots(otley_point)
armley_line = get_raster_line_with_knots(armley_point)
```
::: {#fig-skeleton-line layout-ncol="2"}
```{python}
shapely_transform = partial(affine_transform, matrix=s_matrix_otley)
otley_sk = otley_line.map(shapely_transform).map(set_precision_pointone)
otley_sk = otley_sk.set_crs(CRS)
otley_sk.plot()
```
```{python}
shapely_transform = partial(affine_transform, matrix=s_matrix_armley)
armley_sk = armley_line.map(shapely_transform).map(set_precision_pointone)
armley_sk = armley_sk.set_crs(CRS)
armley_sk.plot()
```
Simplified versions of the Otley Road (left) and Armley Road (right) networks, transformed back into line geometry.
:::
```{python}
#| include: false
import networkx as nx
from shapely.geometry import MultiPoint
def get_raster_line_without_knot(this_line):
"""get_raster_line_without_knot: remove knots from LineString GeoSeries
args:
this_line: LineString GeoSeries array with knots
returns:
LineString GeoSeries with knots removed
"""
edge, node = get_source_target(this_line)
ix = edge.length > 2.0
connected = get_connected_class(edge.loc[~ix, ["source", "target"]])
node = node.loc[connected.index].join(connected).sort_index()
connected_edge = get_centre(node)
r = combine_line(pd.concat([connected_edge["geometry"], edge.loc[ix, "geometry"]]))
return r[r.length > 2.0]
def get_connected_class(edge):
"""get_connected_class: return labeled connected node pandas Series from edge list
args:
edge_list: source, target edge pandas DataFrame
returns:
labeled node pandas Series
"""
nx_graph = nx.from_pandas_edgelist(edge)
connected = nx.connected_components(nx_graph)
r = {k: i for i, j in enumerate(connected) for k in j}
return pd.Series(r, name="class")
def get_centre(node):
"""get_centre_edge: return centroid Point from discrete node clusters
args:
node: discrete node cluster GeoDataSeries
returns:
GeoDataCentre node cluster centroid Point
"""
centre = node[["geometry", "class"]].groupby("class").aggregate(tuple)
centre = gp.GeoSeries(centre["geometry"].map(MultiPoint), crs=CRS).centroid
centre = centre.rename("target")
geometry = node[["class", "geometry"]].set_index("class").join(centre)
geometry = geometry.apply(LineString, axis=1)
r = node.rename(columns={"node": "source"}).copy()
r["geometry"] = geometry.values
return r
```
```{=html}
<!-- ### Primal network
There are circumstances where it might be beneficial to view a "primal" network, which is exclusively composed of direct lines connecting start and end points.
This primal network represents an extreme form of simplification, of great potential value in situations in which the network's overall structure and compression ratios are priorities.
The primal networks for the Otley Road and Armley Road networks are illustrated in @fig-primal. -->
```
```{python}
#| include: false
def get_nx(line):
"""get_nx: return primal edge and node network from LineString GeoDataFrame
args:
line: LineString GeoDataFrame
returns:
edge, node GeoDataFrames
"""
r = line.map(get_end)
edge = gp.GeoSeries(r.map(LineString), crs=CRS)
r = np.vstack(r.to_numpy())
r = gp.GeoSeries(map(Point, r)).to_frame("geometry")
r = r.groupby(r.columns.to_list(), as_index=False).size()
return edge
```
<!-- ::: {#fig-primal layout-ncol="2"} -->
```{python}
#| include: false
otley_edge_sk = get_nx(otley_sk)
otley_edge_sk.plot()
```
```{python}
#| include: false
armley_edge_sk = get_nx(armley_sk)
armley_edge_sk.plot()
```
<!-- Primal networks for the Otley Road (left) and Armley Road (right) networks. -->
<!-- ::: -->
## Simplification via Voronoi polygons {#sec-simplification-via-voronoi-polygons}
In this approach, the buffers described in the previous section are converted into sequences of points.
From these sequences, a centre-line is derived based on a set of Voronoi polygons with the `Shapely` library[@shapely2023] that cover these points which represents the central line of the network.
This approach facilitates the creation of a simplified network representation by focusing on the central alignment of the buffered lines.
The clipped Voronoi representation and the resulting central lines are illustrated in @fig-voronoi-2 and @fig-voronoi-line, respectively.
<!-- ### Boundary Segmentation -->
```{python}
from shapely import box
from shapely.ops import voronoi_diagram
scale = 5.0
tolerance = 0.1
otley_clip = box(426800, 437400, 427000, 437600)
armley_clip = box(427200, 433500, 427400, 433700)
def get_geometry_line(this_buffer):
"""get_geometry_line: returns LineString boundary from geometry
args:
this_buffer: geometry to find LineString
returns:
simplified LineString boundary
"""
r = this_buffer.boundary.explode(index_parts=False).reset_index(drop=True)
return gp.GeoSeries(r.simplify(tolerance=0.5), crs=CRS)
```
```{=html}
<!-- In @fig-boundary, the boundary of the buffered input geometry (otley_geometry) is calculated and then simplified.
This process yields a simplified GeoSeries consisting of LineStrings, all of which are precisely aligned with the specified coordinate reference system (CRS).
This step illustrates the transformation from the initial buffer geometries, named 'otley_buffer' and 'Armley_buffer', to their more refined and simplified versions, 'otley_boundary' and 'Armley_boundary', respectively.
These refined boundaries provide an accurate representation and visualization of the exact limits of the spatial objects involved. -->
```
```{python}
#| include: false
otley_boundary = get_geometry_line(otley_geometry)
otley_boundary.plot()
```
```{python}
#| include: false
armley_boundary = get_geometry_line(armley_geometry)
armley_boundary.plot()
```
<!-- Simplified boundaries of the Otley Road (left) and Armley Road (right) networks. -->
```{python}
#| include: false
def get_segment_nx(line, scale):
"""get_segment_nx: segment line into sections, no more than scale long
args:
line: line to segment
scale: length to segment line
returns:
segmented LineStrings
"""
set_segment = partial(get_segment, distance=scale)
r = line.map(set_segment).explode().rename("geometry")
return gp.GeoDataFrame(r, crs=CRS)
def get_linestring(line):
"""get_linestring: return LineString GeoSeries from line coordinates
args:
line:
returns:
LineString GeoSeries
"""
r = get_coordinates(line)
r = np.stack([gp.points_from_xy(*r[:-1].T), gp.points_from_xy(*r[1:].T)])
return gp.GeoSeries(pd.DataFrame(r.T).apply(LineString, axis=1), crs=CRS).values
def get_segment(line, distance=50.0):
"""get_segment: segment LineString GeoSeries into distance length segments
args:
line: GeoSeries LineString
length: segmentation distance (default value = 50.0)
returns:
GeoSeries of LineStrings of up to length distance
"""
return get_linestring(line.segmentize(distance))
def get_skeleton(geometry, transform, shape):
"""get_skeleton: return skeletonized raster buffer from Shapely geometry
args:
geometry: Shapely geometry to convert to raster buffer
transform: rasterio affine transformation
shape: output buffer px size
returns:
skeltonized numpy array raster buffer
"""
r = rif.rasterize(geometry.values, transform=transform, out_shape=shape)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
r = remove_small_holes(r, 4).astype(np.uint8)
return skeletonize(r).astype(np.uint8)
def get_raster_line(point, knot=False):
"""get_raster_line: return LineString GeoSeries from 1px line raster eliminating knots
args:
point: 1px raster array with knots
returns:
1px line LineString GeoSeries with knots removed
"""
square = point.buffer(1, cap_style="square", mitre_limit=1)
ix = point.sindex.query(square, predicate="covers").T
ix = np.sort(ix)
s = pd.DataFrame(ix).drop_duplicates().reset_index(drop=True)
s = s.loc[np.where(s[0] != s[1])]
s = np.stack([point[s[0].values], point[s[1].values]]).T
r = gp.GeoSeries(map(LineString, s), crs=CRS)
edge, node = get_source_target(combine_line(r).to_frame("geometry"))
if knot:
return combine_line(edge["geometry"])
ix = edge.length > 2.0
connected = get_connected_class(edge.loc[~ix, ["source", "target"]])
node = node.loc[connected.index].join(connected).sort_index()
connected_edge = get_centre(node)
r = combine_line(pd.concat([connected_edge["geometry"], edge.loc[ix, "geometry"]]))
return r[r.length > 2.0]
```
```{=html}
<!-- @fig-segment showcase the conversion of segmented LineString geometries into point geometries.
This essential transformation forms the basis for constructing Voronoi diagrams. -->
```
<!-- ::: {#fig-segment layout-ncol="2"} -->
```{python}
#| include: false
otley_segment = get_segment_nx(otley_boundary, scale).reset_index(drop=True)
ax = otley_segment.clip(otley_clip).plot(edgecolor="red", linestyle='--', linewidth=1)
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
```
```{python}
#| include: false
armley_segment = get_segment_nx(armley_boundary, scale).reset_index(drop=True)
ax = armley_segment.clip(armley_clip).plot(edgecolor="red", linestyle='--', linewidth=1)
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
```
<!-- Detail segmented boundaries of the Otley Road (left) and Armley Road (right) networks. -->
<!-- ::: -->
<!-- @fig-voronoi-point, the process of converting the segmented LineString geometries into point geometries is illustrated. -->
<!-- This transformation is essential for the creation of Voronoi diagrams. -->
<!-- ::: {#fig-voronoi-point layout-ncol="2"} -->
```{python}
#| include: false
otley_point = otley_segment.loc[:, "geometry"].map(get_coordinates).explode()
otley_point = MultiPoint(otley_point[::2].map(Point).values)
nx_output = gp.GeoSeries(otley_point, crs=CRS)
ax = nx_output.clip(otley_clip).plot(edgecolor="blue", color="white")
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
```
```{python}
#| include: false
armley_point = armley_segment.loc[:, "geometry"].map(get_coordinates).explode()
armley_point = MultiPoint(armley_point[::2].map(Point).values)
nx_output = gp.GeoSeries(armley_point, crs=CRS)
ax = nx_output.clip(armley_clip).plot(edgecolor="blue", color="white")
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
```
<!-- Detail point segement of the Otley Road (left) and Armley Road (right) networks. -->
<!-- ::: -->
<!-- we probably want to pick Voronoi #1 or Voronoi #2. I'd marginally favour #2 -->
<!-- In @fig-voronoi-2, the generation and clipping of the corresponding Voronoi diagrams to the bounds of the input geometry is depicted. -->
<!-- ::: {#fig-voronoi layout-ncol="2"} -->
```{python}
#| include: false
otley_envelope = box(*otley_point.bounds)
otley_voronoi = voronoi_diagram(otley_point, envelope=otley_envelope, tolerance=tolerance, edges=True)
otley_voronoi = gp.GeoSeries(map(set_precision_pointone, otley_voronoi.geoms), crs=CRS)
#ax = otley_voronoi.plot()
#ax.xaxis.set_ticklabels([])
#ax.yaxis.set_ticklabels([])
```
```{python}
#| include: false
armley_envelope = box(*armley_point.bounds)
armley_voronoi = voronoi_diagram(armley_point, envelope=armley_envelope, tolerance=tolerance, edges=True)
armley_voronoi = gp.GeoSeries(map(set_precision_pointone, armley_voronoi.geoms), crs=CRS)
#ax = armley_voronoi.plot()
#ax.xaxis.set_ticklabels([])
#ax.yaxis.set_ticklabels([])
```
::: {#fig-voronoi-2 layout-ncol="2"}
```{python}
otley_voronoi = otley_voronoi.explode(index_parts=False).clip(otley_envelope)
ix = ~otley_voronoi.is_empty & (otley_voronoi.type == "LineString")
otley_voronoi = otley_voronoi[ix].reset_index(drop=True)
ax = otley_voronoi.plot()
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])