streetform 0.1.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.
- streetform/__init__.py +77 -0
- streetform/__main__.py +7 -0
- streetform/_geom.py +224 -0
- streetform/_version.py +1 -0
- streetform/blocks.py +181 -0
- streetform/cli.py +146 -0
- streetform/graph.py +531 -0
- streetform/io.py +194 -0
- streetform/metrics.py +452 -0
- streetform/py.typed +0 -0
- streetform/zones.py +205 -0
- streetform-0.1.0.dist-info/METADATA +247 -0
- streetform-0.1.0.dist-info/RECORD +17 -0
- streetform-0.1.0.dist-info/WHEEL +5 -0
- streetform-0.1.0.dist-info/entry_points.txt +2 -0
- streetform-0.1.0.dist-info/licenses/LICENSE +21 -0
- streetform-0.1.0.dist-info/top_level.txt +1 -0
streetform/__init__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""streetform: street-network form and connectivity metrics from GeoJSON lines.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
from streetform import read_lines, build_graph, network_metrics
|
|
6
|
+
|
|
7
|
+
g = build_graph(read_lines("streets.geojson"), crs="auto", tolerance=0.5)
|
|
8
|
+
m = network_metrics(g)
|
|
9
|
+
print(m["intersection_density_per_km2"], m["orientation_order"], m["alpha"])
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from ._geom import LocalProjection
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .blocks import Block, block_metrics, polygonize
|
|
15
|
+
from .graph import Edge, StreetGraph, build_graph, detect_crs
|
|
16
|
+
from .io import (
|
|
17
|
+
blocks_to_geojson,
|
|
18
|
+
edges_to_geojson,
|
|
19
|
+
nodes_to_geojson,
|
|
20
|
+
read_geojson,
|
|
21
|
+
read_lines,
|
|
22
|
+
write_csv,
|
|
23
|
+
write_geojson,
|
|
24
|
+
)
|
|
25
|
+
from .metrics import (
|
|
26
|
+
connectivity_metrics,
|
|
27
|
+
degree_distribution,
|
|
28
|
+
edge_circuity,
|
|
29
|
+
kansky_indices,
|
|
30
|
+
network_metrics,
|
|
31
|
+
order_from_entropy,
|
|
32
|
+
orientation_entropy,
|
|
33
|
+
orientation_histogram,
|
|
34
|
+
orientation_order,
|
|
35
|
+
route_directness,
|
|
36
|
+
sampled_circuity,
|
|
37
|
+
shortest_path_lengths,
|
|
38
|
+
study_area,
|
|
39
|
+
)
|
|
40
|
+
from .zones import Zone, grid_zones, read_zones, summarize_zones, zones_to_geojson
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"__version__",
|
|
44
|
+
"Block",
|
|
45
|
+
"Edge",
|
|
46
|
+
"LocalProjection",
|
|
47
|
+
"StreetGraph",
|
|
48
|
+
"Zone",
|
|
49
|
+
"block_metrics",
|
|
50
|
+
"blocks_to_geojson",
|
|
51
|
+
"build_graph",
|
|
52
|
+
"connectivity_metrics",
|
|
53
|
+
"degree_distribution",
|
|
54
|
+
"detect_crs",
|
|
55
|
+
"edge_circuity",
|
|
56
|
+
"edges_to_geojson",
|
|
57
|
+
"grid_zones",
|
|
58
|
+
"kansky_indices",
|
|
59
|
+
"network_metrics",
|
|
60
|
+
"nodes_to_geojson",
|
|
61
|
+
"orientation_entropy",
|
|
62
|
+
"orientation_histogram",
|
|
63
|
+
"orientation_order",
|
|
64
|
+
"order_from_entropy",
|
|
65
|
+
"polygonize",
|
|
66
|
+
"read_geojson",
|
|
67
|
+
"read_lines",
|
|
68
|
+
"read_zones",
|
|
69
|
+
"route_directness",
|
|
70
|
+
"sampled_circuity",
|
|
71
|
+
"shortest_path_lengths",
|
|
72
|
+
"study_area",
|
|
73
|
+
"summarize_zones",
|
|
74
|
+
"write_csv",
|
|
75
|
+
"write_geojson",
|
|
76
|
+
"zones_to_geojson",
|
|
77
|
+
]
|
streetform/__main__.py
ADDED
streetform/_geom.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Small planar-geometry helpers (pure Python, no dependencies)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import List, Optional, Sequence, Tuple
|
|
7
|
+
|
|
8
|
+
Point = Tuple[float, float]
|
|
9
|
+
Ring = List[Point]
|
|
10
|
+
|
|
11
|
+
EARTH_RADIUS_M = 6371008.8
|
|
12
|
+
"""Mean Earth radius (IUGG), used by the local lon/lat projection."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LocalProjection:
|
|
16
|
+
"""Map coordinates to a planar metric frame and back.
|
|
17
|
+
|
|
18
|
+
For ``kind="lonlat"`` an equirectangular projection centred on
|
|
19
|
+
``(lon0, lat0)`` is used: ``x = R * dlon * cos(lat0)``, ``y = R * dlat``
|
|
20
|
+
(radians, ``R`` = mean Earth radius). Its scale error grows with the
|
|
21
|
+
north-south extent (roughly ``tan(lat0) * dlat``; about 0.15 % for
|
|
22
|
+
+/- 0.1 degree at 41 degrees N), which is acceptable for neighbourhood- to
|
|
23
|
+
city-scale analysis. For ``kind="projected"`` coordinates pass through
|
|
24
|
+
unchanged and are assumed to be in metres.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, kind: str = "projected", lon0: float = 0.0, lat0: float = 0.0) -> None:
|
|
28
|
+
if kind not in ("projected", "lonlat"):
|
|
29
|
+
raise ValueError("kind must be 'projected' or 'lonlat'")
|
|
30
|
+
self.kind = kind
|
|
31
|
+
self.lon0 = lon0
|
|
32
|
+
self.lat0 = lat0
|
|
33
|
+
self._kx = EARTH_RADIUS_M * math.cos(math.radians(lat0)) * math.pi / 180.0
|
|
34
|
+
self._ky = EARTH_RADIUS_M * math.pi / 180.0
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def is_geographic(self) -> bool:
|
|
38
|
+
return self.kind == "lonlat"
|
|
39
|
+
|
|
40
|
+
def forward(self, p: Sequence[float]) -> Point:
|
|
41
|
+
if self.kind == "projected":
|
|
42
|
+
return (float(p[0]), float(p[1]))
|
|
43
|
+
return ((float(p[0]) - self.lon0) * self._kx, (float(p[1]) - self.lat0) * self._ky)
|
|
44
|
+
|
|
45
|
+
def inverse(self, p: Sequence[float]) -> Point:
|
|
46
|
+
if self.kind == "projected":
|
|
47
|
+
return (float(p[0]), float(p[1]))
|
|
48
|
+
return (p[0] / self._kx + self.lon0, p[1] / self._ky + self.lat0)
|
|
49
|
+
|
|
50
|
+
def __repr__(self) -> str:
|
|
51
|
+
if self.kind == "projected":
|
|
52
|
+
return "LocalProjection('projected')"
|
|
53
|
+
return f"LocalProjection('lonlat', lon0={self.lon0:.6f}, lat0={self.lat0:.6f})"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def dist(a: Point, b: Point) -> float:
|
|
57
|
+
return math.hypot(b[0] - a[0], b[1] - a[1])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def polyline_length(coords: Sequence[Point]) -> float:
|
|
61
|
+
return sum(dist(coords[i], coords[i + 1]) for i in range(len(coords) - 1))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def interpolate(coords: Sequence[Point], fraction: float) -> Point:
|
|
65
|
+
"""Point at ``fraction`` (0..1) of the length along a polyline."""
|
|
66
|
+
total = polyline_length(coords)
|
|
67
|
+
if total == 0.0:
|
|
68
|
+
return coords[0]
|
|
69
|
+
target = fraction * total
|
|
70
|
+
acc = 0.0
|
|
71
|
+
for i in range(len(coords) - 1):
|
|
72
|
+
seg = dist(coords[i], coords[i + 1])
|
|
73
|
+
if acc + seg >= target and seg > 0:
|
|
74
|
+
t = (target - acc) / seg
|
|
75
|
+
a, b = coords[i], coords[i + 1]
|
|
76
|
+
return (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))
|
|
77
|
+
acc += seg
|
|
78
|
+
return coords[-1]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def bearing(a: Point, b: Point) -> Optional[float]:
|
|
82
|
+
"""Compass bearing from ``a`` to ``b`` in degrees, 0 = north, clockwise."""
|
|
83
|
+
dx, dy = b[0] - a[0], b[1] - a[1]
|
|
84
|
+
if dx == 0.0 and dy == 0.0:
|
|
85
|
+
return None
|
|
86
|
+
return math.degrees(math.atan2(dx, dy)) % 360.0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def signed_area(ring: Sequence[Point]) -> float:
|
|
90
|
+
"""Shoelace signed area; positive for counter-clockwise rings."""
|
|
91
|
+
n = len(ring)
|
|
92
|
+
if n < 3:
|
|
93
|
+
return 0.0
|
|
94
|
+
s = 0.0
|
|
95
|
+
for i in range(n):
|
|
96
|
+
x1, y1 = ring[i]
|
|
97
|
+
x2, y2 = ring[(i + 1) % n]
|
|
98
|
+
s += x1 * y2 - x2 * y1
|
|
99
|
+
return 0.5 * s
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def point_in_ring(pt: Point, ring: Sequence[Point]) -> bool:
|
|
103
|
+
"""Even-odd ray casting test (the closing vertex may be repeated or not)."""
|
|
104
|
+
x, y = pt
|
|
105
|
+
inside = False
|
|
106
|
+
n = len(ring)
|
|
107
|
+
j = n - 1
|
|
108
|
+
for i in range(n):
|
|
109
|
+
xi, yi = ring[i]
|
|
110
|
+
xj, yj = ring[j]
|
|
111
|
+
if (yi > y) != (yj > y):
|
|
112
|
+
xint = xi + (y - yi) * (xj - xi) / (yj - yi)
|
|
113
|
+
if x < xint:
|
|
114
|
+
inside = not inside
|
|
115
|
+
j = i
|
|
116
|
+
return inside
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def point_in_polygon(pt: Point, rings: Sequence[Sequence[Point]]) -> bool:
|
|
120
|
+
"""``rings[0]`` is the exterior, the rest are holes."""
|
|
121
|
+
if not rings or not point_in_ring(pt, rings[0]):
|
|
122
|
+
return False
|
|
123
|
+
return not any(point_in_ring(pt, h) for h in rings[1:])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def project_point_on_segment(p: Point, a: Point, b: Point) -> Tuple[float, Point, float]:
|
|
127
|
+
"""Return ``(t, foot, distance)`` of the closest point to ``p`` on ``ab``."""
|
|
128
|
+
dx, dy = b[0] - a[0], b[1] - a[1]
|
|
129
|
+
den = dx * dx + dy * dy
|
|
130
|
+
if den == 0.0:
|
|
131
|
+
return 0.0, a, dist(p, a)
|
|
132
|
+
t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / den
|
|
133
|
+
t = 0.0 if t < 0.0 else (1.0 if t > 1.0 else t)
|
|
134
|
+
foot = (a[0] + t * dx, a[1] + t * dy)
|
|
135
|
+
return t, foot, dist(p, foot)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def segment_intersection(
|
|
139
|
+
p: Point, p2: Point, q: Point, q2: Point
|
|
140
|
+
) -> Optional[Tuple[float, float, Point]]:
|
|
141
|
+
"""Proper (non-parallel) intersection of segments ``p-p2`` and ``q-q2``.
|
|
142
|
+
|
|
143
|
+
Returns ``(t, u, point)`` with ``t, u`` in [0, 1] or ``None``.
|
|
144
|
+
"""
|
|
145
|
+
rx, ry = p2[0] - p[0], p2[1] - p[1]
|
|
146
|
+
sx, sy = q2[0] - q[0], q2[1] - q[1]
|
|
147
|
+
den = rx * sy - ry * sx
|
|
148
|
+
scale = math.hypot(rx, ry) * math.hypot(sx, sy)
|
|
149
|
+
if scale == 0.0 or abs(den) <= 1e-12 * scale:
|
|
150
|
+
return None
|
|
151
|
+
qpx, qpy = q[0] - p[0], q[1] - p[1]
|
|
152
|
+
t = (qpx * sy - qpy * sx) / den
|
|
153
|
+
u = (qpx * ry - qpy * rx) / den
|
|
154
|
+
eps = 1e-12
|
|
155
|
+
if -eps <= t <= 1 + eps and -eps <= u <= 1 + eps:
|
|
156
|
+
t = min(max(t, 0.0), 1.0)
|
|
157
|
+
u = min(max(u, 0.0), 1.0)
|
|
158
|
+
return t, u, (p[0] + t * rx, p[1] + t * ry)
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def convex_hull(points: Sequence[Point]) -> Ring:
|
|
163
|
+
"""Andrew's monotone chain; counter-clockwise hull without repeated vertex."""
|
|
164
|
+
pts = sorted(set(points))
|
|
165
|
+
if len(pts) <= 2:
|
|
166
|
+
return list(pts)
|
|
167
|
+
|
|
168
|
+
def cross(o: Point, a: Point, b: Point) -> float:
|
|
169
|
+
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
|
170
|
+
|
|
171
|
+
lower: Ring = []
|
|
172
|
+
for pt in pts:
|
|
173
|
+
while len(lower) >= 2 and cross(lower[-2], lower[-1], pt) <= 0:
|
|
174
|
+
lower.pop()
|
|
175
|
+
lower.append(pt)
|
|
176
|
+
upper: Ring = []
|
|
177
|
+
for pt in reversed(pts):
|
|
178
|
+
while len(upper) >= 2 and cross(upper[-2], upper[-1], pt) <= 0:
|
|
179
|
+
upper.pop()
|
|
180
|
+
upper.append(pt)
|
|
181
|
+
return lower[:-1] + upper[:-1]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def ring_perimeter(ring: Sequence[Point]) -> float:
|
|
185
|
+
n = len(ring)
|
|
186
|
+
return sum(dist(ring[i], ring[(i + 1) % n]) for i in range(n))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def representative_point(ring: Sequence[Point]) -> Point:
|
|
190
|
+
"""A point inside a simple polygon ring (centroid when it lies inside).
|
|
191
|
+
|
|
192
|
+
Falls back to a horizontal scan-line midpoint for concave rings.
|
|
193
|
+
"""
|
|
194
|
+
a = signed_area(ring)
|
|
195
|
+
n = len(ring)
|
|
196
|
+
if a != 0.0:
|
|
197
|
+
cx = cy = 0.0
|
|
198
|
+
for i in range(n):
|
|
199
|
+
x1, y1 = ring[i]
|
|
200
|
+
x2, y2 = ring[(i + 1) % n]
|
|
201
|
+
f = x1 * y2 - x2 * y1
|
|
202
|
+
cx += (x1 + x2) * f
|
|
203
|
+
cy += (y1 + y2) * f
|
|
204
|
+
c = (cx / (6 * a), cy / (6 * a))
|
|
205
|
+
if point_in_ring(c, ring):
|
|
206
|
+
return c
|
|
207
|
+
ys = sorted({p[1] for p in ring})
|
|
208
|
+
best: Optional[Point] = None
|
|
209
|
+
best_w = -1.0
|
|
210
|
+
for k in range(len(ys) - 1):
|
|
211
|
+
y = 0.5 * (ys[k] + ys[k + 1])
|
|
212
|
+
xs = []
|
|
213
|
+
for i in range(n):
|
|
214
|
+
x1, y1 = ring[i]
|
|
215
|
+
x2, y2 = ring[(i + 1) % n]
|
|
216
|
+
if (y1 > y) != (y2 > y):
|
|
217
|
+
xs.append(x1 + (y - y1) * (x2 - x1) / (y2 - y1))
|
|
218
|
+
xs.sort()
|
|
219
|
+
for j in range(0, len(xs) - 1, 2):
|
|
220
|
+
w = xs[j + 1] - xs[j]
|
|
221
|
+
if w > best_w:
|
|
222
|
+
best_w = w
|
|
223
|
+
best = (0.5 * (xs[j] + xs[j + 1]), y)
|
|
224
|
+
return best if best is not None else ring[0]
|
streetform/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
streetform/blocks.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Urban blocks as the bounded faces of the planar street graph."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import statistics
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
from ._geom import Point, point_in_ring, signed_area
|
|
11
|
+
from .graph import StreetGraph
|
|
12
|
+
|
|
13
|
+
__all__ = ["Block", "polygonize", "block_metrics"]
|
|
14
|
+
|
|
15
|
+
HalfEdge = Tuple[int, bool] # (edge id, forward?)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Block:
|
|
20
|
+
"""A bounded face of the planar street graph.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
ring: exterior ring (planar metres, counter-clockwise, not closed).
|
|
24
|
+
Cul-de-sacs reaching into the block appear as zero-width spikes.
|
|
25
|
+
holes: rings of street components lying entirely inside the block.
|
|
26
|
+
area: area in m2 (exterior minus holes).
|
|
27
|
+
perimeter: length of the bounding streets in metres, excluding
|
|
28
|
+
cul-de-sacs that only reach into the block (their two sides both
|
|
29
|
+
belong to it) and excluding holes.
|
|
30
|
+
edge_ids: ids of the links on the block boundary.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
id: int
|
|
34
|
+
ring: List[Point]
|
|
35
|
+
area: float
|
|
36
|
+
perimeter: float
|
|
37
|
+
holes: List[List[Point]] = field(default_factory=list)
|
|
38
|
+
edge_ids: List[int] = field(default_factory=list)
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def compactness(self) -> Optional[float]:
|
|
42
|
+
"""Isoperimetric quotient ``4 pi A / P**2`` (1 for a circle)."""
|
|
43
|
+
if self.perimeter <= 0:
|
|
44
|
+
return None
|
|
45
|
+
return 4.0 * math.pi * self.area / self.perimeter**2
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _faces(graph: StreetGraph) -> Tuple[List[List[HalfEdge]], Dict[HalfEdge, int]]:
|
|
49
|
+
out_by_node: Dict[int, List[Tuple[float, HalfEdge]]] = {n: [] for n in graph.nodes}
|
|
50
|
+
for e in graph.edges.values():
|
|
51
|
+
c = e.coords
|
|
52
|
+
a0 = math.atan2(c[1][1] - c[0][1], c[1][0] - c[0][0])
|
|
53
|
+
a1 = math.atan2(c[-2][1] - c[-1][1], c[-2][0] - c[-1][0])
|
|
54
|
+
out_by_node[e.u].append((a0, (e.id, True)))
|
|
55
|
+
out_by_node[e.v].append((a1, (e.id, False)))
|
|
56
|
+
order: Dict[int, List[HalfEdge]] = {}
|
|
57
|
+
index: Dict[HalfEdge, int] = {}
|
|
58
|
+
for n, lst in out_by_node.items():
|
|
59
|
+
lst.sort(key=lambda t: (t[0], t[1]))
|
|
60
|
+
order[n] = [h for _, h in lst]
|
|
61
|
+
for i, h in enumerate(order[n]):
|
|
62
|
+
index[h] = i
|
|
63
|
+
|
|
64
|
+
def dest(h: HalfEdge) -> int:
|
|
65
|
+
e = graph.edges[h[0]]
|
|
66
|
+
return e.v if h[1] else e.u
|
|
67
|
+
|
|
68
|
+
face_of: Dict[HalfEdge, int] = {}
|
|
69
|
+
faces: List[List[HalfEdge]] = []
|
|
70
|
+
for start in index:
|
|
71
|
+
if start in face_of:
|
|
72
|
+
continue
|
|
73
|
+
fid = len(faces)
|
|
74
|
+
cyc: List[HalfEdge] = []
|
|
75
|
+
h = start
|
|
76
|
+
while h not in face_of:
|
|
77
|
+
face_of[h] = fid
|
|
78
|
+
cyc.append(h)
|
|
79
|
+
twin = (h[0], not h[1])
|
|
80
|
+
ring_order = order[dest(h)]
|
|
81
|
+
h = ring_order[(index[twin] - 1) % len(ring_order)]
|
|
82
|
+
faces.append(cyc)
|
|
83
|
+
return faces, face_of
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _ring(graph: StreetGraph, cyc: List[HalfEdge]) -> List[Point]:
|
|
87
|
+
ring: List[Point] = []
|
|
88
|
+
for eid, fwd in cyc:
|
|
89
|
+
c = graph.edges[eid].coords
|
|
90
|
+
seq = c if fwd else list(reversed(c))
|
|
91
|
+
ring.extend(seq[:-1])
|
|
92
|
+
return ring
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def polygonize(
|
|
96
|
+
graph: StreetGraph, min_area: float = 0.0, max_area: Optional[float] = None
|
|
97
|
+
) -> List[Block]:
|
|
98
|
+
"""Extract blocks (bounded faces) from a planar street graph.
|
|
99
|
+
|
|
100
|
+
Faces are traced on the half-edge structure of the embedded graph (at
|
|
101
|
+
each node the next half-edge is the one immediately clockwise of the
|
|
102
|
+
incoming twin), so each bounded face is a counter-clockwise cycle with
|
|
103
|
+
positive area. Street components lying inside a face become its holes.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
min_area: discard faces smaller than this (m2), e.g. slivers between
|
|
107
|
+
dual carriageways.
|
|
108
|
+
max_area: discard faces larger than this (m2).
|
|
109
|
+
|
|
110
|
+
Raises:
|
|
111
|
+
ValueError: if the graph was built with ``split_crossings=False``.
|
|
112
|
+
"""
|
|
113
|
+
if not graph.planar:
|
|
114
|
+
raise ValueError("blocks need a planar graph (build_graph(split_crossings=True))")
|
|
115
|
+
faces, face_of = _faces(graph)
|
|
116
|
+
comp = graph.components()
|
|
117
|
+
eps = 1e-9
|
|
118
|
+
bounded: List[Tuple[int, List[Point], float, int]] = []
|
|
119
|
+
outers: List[Tuple[List[Point], int]] = []
|
|
120
|
+
for fid, cyc in enumerate(faces):
|
|
121
|
+
ring = _ring(graph, cyc)
|
|
122
|
+
a = signed_area(ring)
|
|
123
|
+
c = comp[graph.edges[cyc[0][0]].u]
|
|
124
|
+
if a > eps:
|
|
125
|
+
bounded.append((fid, ring, a, c))
|
|
126
|
+
elif a < -eps:
|
|
127
|
+
outers.append((ring, c))
|
|
128
|
+
|
|
129
|
+
# The outer boundary of a street component that lies inside a bounded
|
|
130
|
+
# face of another component is a hole of that face.
|
|
131
|
+
holes: Dict[int, List[List[Point]]] = {}
|
|
132
|
+
for ring, c in outers:
|
|
133
|
+
probe = ring[0]
|
|
134
|
+
best: Optional[Tuple[float, int]] = None
|
|
135
|
+
for fid, fring, a, fc in bounded:
|
|
136
|
+
if fc == c:
|
|
137
|
+
continue
|
|
138
|
+
if (best is None or a < best[0]) and point_in_ring(probe, fring):
|
|
139
|
+
best = (a, fid)
|
|
140
|
+
if best is not None:
|
|
141
|
+
holes.setdefault(best[1], []).append(list(reversed(ring)))
|
|
142
|
+
|
|
143
|
+
blocks: List[Block] = []
|
|
144
|
+
for fid, ring, a, _ in bounded:
|
|
145
|
+
hs = holes.get(fid, [])
|
|
146
|
+
area = a - sum(abs(signed_area(h)) for h in hs)
|
|
147
|
+
if area < min_area or (max_area is not None and area > max_area):
|
|
148
|
+
continue
|
|
149
|
+
perim = 0.0
|
|
150
|
+
eids: List[int] = []
|
|
151
|
+
for eid, fwd in faces[fid]:
|
|
152
|
+
if face_of[(eid, not fwd)] == fid:
|
|
153
|
+
continue # both sides in this face: a dangle, not a boundary
|
|
154
|
+
perim += graph.edges[eid].length
|
|
155
|
+
if eid not in eids:
|
|
156
|
+
eids.append(eid)
|
|
157
|
+
blocks.append(Block(len(blocks), ring, area, perim, hs, eids))
|
|
158
|
+
return blocks
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def block_metrics(
|
|
162
|
+
graph: StreetGraph, min_area: float = 0.0, max_area: Optional[float] = None
|
|
163
|
+
) -> Dict[str, Any]:
|
|
164
|
+
"""Summary of block size: count, total/mean/median area and perimeter.
|
|
165
|
+
|
|
166
|
+
Mean block area and median block perimeter are classic measures of urban
|
|
167
|
+
grain and connectivity (reviewed in Dill 2004, Table 1).
|
|
168
|
+
"""
|
|
169
|
+
blocks = polygonize(graph, min_area, max_area)
|
|
170
|
+
areas = [b.area for b in blocks]
|
|
171
|
+
perims = [b.perimeter for b in blocks]
|
|
172
|
+
comp = [b.compactness for b in blocks if b.compactness is not None]
|
|
173
|
+
return {
|
|
174
|
+
"blocks": len(blocks),
|
|
175
|
+
"block_area_total_m2": sum(areas),
|
|
176
|
+
"block_area_mean_m2": statistics.fmean(areas) if areas else None,
|
|
177
|
+
"block_area_median_m2": statistics.median(areas) if areas else None,
|
|
178
|
+
"block_perimeter_mean_m": statistics.fmean(perims) if perims else None,
|
|
179
|
+
"block_perimeter_median_m": statistics.median(perims) if perims else None,
|
|
180
|
+
"block_compactness_mean": statistics.fmean(comp) if comp else None,
|
|
181
|
+
}
|
streetform/cli.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Command-line interface: ``streetform metrics|export|zones``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import List, Optional
|
|
10
|
+
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .graph import StreetGraph, build_graph
|
|
13
|
+
from .io import (
|
|
14
|
+
blocks_to_geojson,
|
|
15
|
+
edges_to_geojson,
|
|
16
|
+
nodes_to_geojson,
|
|
17
|
+
read_lines,
|
|
18
|
+
write_csv,
|
|
19
|
+
write_geojson,
|
|
20
|
+
)
|
|
21
|
+
from .metrics import network_metrics
|
|
22
|
+
from .zones import grid_zones, read_zones, summarize_zones, zones_to_geojson
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _add_graph_args(p: argparse.ArgumentParser) -> None:
|
|
26
|
+
p.add_argument("input", help="GeoJSON with LineString/MultiLineString street centrelines")
|
|
27
|
+
p.add_argument(
|
|
28
|
+
"--crs",
|
|
29
|
+
choices=["auto", "projected", "lonlat"],
|
|
30
|
+
default="auto",
|
|
31
|
+
help="coordinate system of the input (projected = metres; default: auto)",
|
|
32
|
+
)
|
|
33
|
+
p.add_argument(
|
|
34
|
+
"-t", "--tolerance", type=float, default=0.5, help="snapping tolerance in m (0.5)"
|
|
35
|
+
)
|
|
36
|
+
p.add_argument(
|
|
37
|
+
"--no-split",
|
|
38
|
+
action="store_true",
|
|
39
|
+
help="do not split at crossings (keeps bridges/tunnels unconnected; disables blocks)",
|
|
40
|
+
)
|
|
41
|
+
p.add_argument("--keep-degree2", action="store_true", help="do not dissolve degree-2 nodes")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _graph(args: argparse.Namespace) -> StreetGraph:
|
|
45
|
+
lines = read_lines(args.input)
|
|
46
|
+
if not lines:
|
|
47
|
+
raise SystemExit(f"streetform: no LineString features in {args.input}")
|
|
48
|
+
return build_graph(
|
|
49
|
+
lines,
|
|
50
|
+
crs=args.crs,
|
|
51
|
+
tolerance=args.tolerance,
|
|
52
|
+
split_crossings=not args.no_split,
|
|
53
|
+
simplify=not args.keep_degree2,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _cmd_metrics(args: argparse.Namespace) -> int:
|
|
58
|
+
g = _graph(args)
|
|
59
|
+
m = network_metrics(g, area_m2=args.area_m2, n_pairs=args.pairs, seed=args.seed)
|
|
60
|
+
m = {"crs": g.projection.kind, **m}
|
|
61
|
+
text = json.dumps(m, indent=2, ensure_ascii=False)
|
|
62
|
+
if args.output:
|
|
63
|
+
out = Path(args.output)
|
|
64
|
+
if out.suffix.lower() == ".csv":
|
|
65
|
+
flat = {k: v for k, v in m.items() if not isinstance(v, dict)}
|
|
66
|
+
for d, c in m["degree_distribution"].items():
|
|
67
|
+
flat[f"degree_{d}"] = c
|
|
68
|
+
write_csv([flat], out)
|
|
69
|
+
else:
|
|
70
|
+
out.write_text(text + "\n", encoding="utf-8")
|
|
71
|
+
else:
|
|
72
|
+
print(text)
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _cmd_export(args: argparse.Namespace) -> int:
|
|
77
|
+
g = _graph(args)
|
|
78
|
+
if not (args.nodes or args.edges or args.blocks):
|
|
79
|
+
raise SystemExit("streetform export: give at least one of --nodes, --edges, --blocks")
|
|
80
|
+
if args.nodes:
|
|
81
|
+
write_geojson(nodes_to_geojson(g), args.nodes)
|
|
82
|
+
if args.edges:
|
|
83
|
+
write_geojson(edges_to_geojson(g), args.edges)
|
|
84
|
+
if args.blocks:
|
|
85
|
+
write_geojson(blocks_to_geojson(g, min_area=args.min_block_area), args.blocks)
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _cmd_zones(args: argparse.Namespace) -> int:
|
|
90
|
+
g = _graph(args)
|
|
91
|
+
if (args.zones is None) == (args.grid is None):
|
|
92
|
+
raise SystemExit("streetform zones: give exactly one of --zones or --grid")
|
|
93
|
+
zones = read_zones(args.zones, args.id_field) if args.zones else grid_zones(g, args.grid)
|
|
94
|
+
rows = summarize_zones(g, zones, n_pairs=args.pairs, seed=args.seed)
|
|
95
|
+
out = Path(args.output)
|
|
96
|
+
if out.suffix.lower() in (".geojson", ".json"):
|
|
97
|
+
write_geojson(zones_to_geojson(zones, rows), out)
|
|
98
|
+
else:
|
|
99
|
+
write_csv(rows, out)
|
|
100
|
+
print(f"{len(rows)} zones written to {out}")
|
|
101
|
+
return 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
105
|
+
parser = argparse.ArgumentParser(
|
|
106
|
+
prog="streetform",
|
|
107
|
+
description="Street-network form and connectivity metrics from GeoJSON lines.",
|
|
108
|
+
)
|
|
109
|
+
parser.add_argument("--version", action="version", version=f"streetform {__version__}")
|
|
110
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
111
|
+
|
|
112
|
+
pm = sub.add_parser("metrics", help="network-wide metrics as JSON (or one-row CSV)")
|
|
113
|
+
_add_graph_args(pm)
|
|
114
|
+
pm.add_argument("--area-m2", type=float, default=None, help="study area (default: hull)")
|
|
115
|
+
pm.add_argument("--pairs", type=int, default=500, help="node pairs for circuity (500)")
|
|
116
|
+
pm.add_argument("--seed", type=int, default=0, help="random seed for pair sampling")
|
|
117
|
+
pm.add_argument("-o", "--output", help="write to .json or .csv instead of stdout")
|
|
118
|
+
pm.set_defaults(func=_cmd_metrics)
|
|
119
|
+
|
|
120
|
+
pe = sub.add_parser("export", help="write nodes, links and blocks as GeoJSON")
|
|
121
|
+
_add_graph_args(pe)
|
|
122
|
+
pe.add_argument("--nodes", help="output GeoJSON for nodes")
|
|
123
|
+
pe.add_argument("--edges", help="output GeoJSON for links")
|
|
124
|
+
pe.add_argument("--blocks", help="output GeoJSON for blocks (faces)")
|
|
125
|
+
pe.add_argument("--min-block-area", type=float, default=0.0, help="drop smaller faces (m2)")
|
|
126
|
+
pe.set_defaults(func=_cmd_export)
|
|
127
|
+
|
|
128
|
+
pz = sub.add_parser("zones", help="metrics per zone polygon or grid cell")
|
|
129
|
+
_add_graph_args(pz)
|
|
130
|
+
pz.add_argument("--zones", help="GeoJSON with zone polygons (same CRS as the streets)")
|
|
131
|
+
pz.add_argument("--id-field", help="zone id property")
|
|
132
|
+
pz.add_argument("--grid", type=float, help="square grid cell size in metres")
|
|
133
|
+
pz.add_argument("--pairs", type=int, default=0, help="node pairs per zone for circuity")
|
|
134
|
+
pz.add_argument("--seed", type=int, default=0)
|
|
135
|
+
pz.add_argument("-o", "--output", required=True, help="output .csv or .geojson")
|
|
136
|
+
pz.set_defaults(func=_cmd_zones)
|
|
137
|
+
return parser
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
141
|
+
args = build_parser().parse_args(argv)
|
|
142
|
+
try:
|
|
143
|
+
return int(args.func(args))
|
|
144
|
+
except (OSError, ValueError) as exc:
|
|
145
|
+
print(f"streetform: error: {exc}", file=sys.stderr)
|
|
146
|
+
return 1
|