File size: 10,816 Bytes
b6f453a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Sreda ML: pedestrian-level wind speed from building footprints and heights.

Reference preprocessing and inference for the ONNX model in this repository. It builds the model inputs exactly as the
Sreda web app does, runs the model and returns K = <|U|> / U_in at 1.75 m above ground on a 0.75 m grid.

Requirements: numpy, onnxruntime.

    python sreda_ml_example.py model.onnx

Coordinates: scene metres, x to the east, y to the north. Wind direction: where the wind blows from, degrees clockwise
from north. Buildings: dicts with "footprint" (list of [x, y] vertices, any orientation, not closed) and "height" in
metres above flat ground.
"""
import math
import sys

import numpy as np

STEP = 0.75                 # model grid, m
WIN, NW = 150.0, 200        # prediction window: metres and cells
FR, FC = 288, 352           # model frame: rows across the wind x columns along the wind
UP, SIDE = 96.0, 33.0       # frame margins around the window: upwind and on each side, m (downwind: 18 m)
ROW0, COL0 = 44, 128        # window position inside the frame, cells
DMAX = 50.0                 # wall distances beyond 50 m are not resolved
SPACING, KMAX, MARGIN, TAPER = 120.0, 4, 20.0, 40   # mosaic for larger sites, as in the Sreda app
CTX_S0, CTX_T0, CTX_STEP, CTX_ALONG, CTX_ACROSS, CTX_SUB = -435.0, -300.0, 6.0, 88, 100, 4
# Inflow speed at 1.75 m per unit wind speed at 10 m: log profile with roughness length z0 = 0.5 m (0.494).
U_IN_PED = math.log((1.75 + 0.5) / 0.5) / math.log((10 + 0.5) / 0.5)


def wind_axes(from_deg):
    """Unit vectors in scene coordinates: along the flow (ax) and across it (ay, ax turned by +90 degrees)."""
    phi = math.radians(from_deg)
    fa = math.atan2(-math.cos(phi), -math.sin(phi))
    return (math.cos(fa), math.sin(fa)), (-math.sin(fa), math.cos(fa))


def _ground(buildings):
    return [b for b in buildings
            if len(b["footprint"]) >= 3 and float(b.get("base", 0.0)) <= 0.01 and float(b["height"]) > 0]


def raster(buildings, origin, from_deg, s0, t0, ns, nt, step=STEP, heights_only=False):
    """Building top height H and signed distance to the nearest wall (inside a building: minus the depth below its outline),
    on cell centres s0 + (i + 0.5) * step along the wind and t0 + (j + 0.5) * step across it, in metres from origin.
    Returns float32 arrays [nt, ns]; distances further than DMAX stay DMAX."""
    ax, ay = wind_axes(from_deg)
    H = np.zeros((nt, ns), np.float32)
    dist = np.full((nt, ns), DMAX, np.float32)
    depth = np.zeros((nt, ns), np.float32)
    reach = 0.0 if heights_only else DMAX
    for b in _ground(buildings):
        p = np.asarray(b["footprint"], np.float64)
        top = float(b.get("base", 0.0)) + float(b["height"])
        dx, dy = p[:, 0] - origin[0], p[:, 1] - origin[1]
        sa, ta = dx * ax[0] + dy * ax[1], dx * ay[0] + dy * ay[1]       # vertex a
        sc, tc = np.roll(sa, 1), np.roll(ta, 1)                         # previous vertex c: edge c -> a
        smin, smax, tmin, tmax = sa.min(), sa.max(), ta.min(), ta.max()
        i0 = max(0, math.floor((smin - reach - s0) / step))
        i1 = min(ns - 1, math.ceil((smax + reach - s0) / step))
        j0 = max(0, math.floor((tmin - reach - t0) / step))
        j1 = min(nt - 1, math.ceil((tmax + reach - t0) / step))
        if i0 > i1 or j0 > j1:
            continue
        S = s0 + (np.arange(i0, i1 + 1) + 0.5) * step                  # [ni]
        T = t0 + (np.arange(j0, j1 + 1) + 0.5) * step                  # [nj]
        # Inside: even-odd rule along each row (edge crossings of the line t = const left of the cell centre).
        tt = T[:, None]
        cross = (ta[None, :] > tt) != (tc[None, :] > tt)               # [nj, m]
        den = np.where(cross, tc - ta, 1.0)
        xs = np.where(cross, sa + (tt - ta) * (sc - sa) / den, np.inf)
        count = (xs[:, None, :] <= S[None, :, None]).sum(-1)           # [nj, ni]
        box = (S[None, :] >= smin) & (S[None, :] <= smax) & (tt >= tmin) & (tt <= tmax)
        inside = box & (count % 2 == 1)
        h = H[j0:j1 + 1, i0:i1 + 1]
        h[inside & (top > h)] = top
        if heights_only:
            continue
        # Exact distance to the outline: nearest point on each edge.
        ex, ey = sa - sc, ta - tc
        ll = ex * ex + ey * ey
        px, py = S[None, :, None], T[:, None, None]
        u = np.where(ll > 0, ((px - sc) * ex + (py - tc) * ey) / np.where(ll > 0, ll, 1.0), 0.0)
        u = np.clip(u, 0.0, 1.0)
        qx, qy = sc + u * ex - px, tc + u * ey - py
        d = np.sqrt((qx * qx + qy * qy).min(-1))                       # [nj, ni]
        dep = depth[j0:j1 + 1, i0:i1 + 1]
        dep[inside & (d > dep)] = d[inside & (d > dep)]
        dis = dist[j0:j1 + 1, i0:i1 + 1]
        out = ~inside & (d < dis)
        dis[out] = d[out]
    sdf = np.where(H > 0, -depth, dist).astype(np.float32)
    return H, sdf


def frame_channels(H, sdf, r0=0, c0=0):
    """Model frame [3, FR, FC] cut at (r0, c0): building mask, height / 30 m, wall distance / 10 m clipped to [-2, 5]."""
    h = H[r0:r0 + FR, c0:c0 + FC].astype(np.float64)
    d = sdf[r0:r0 + FR, c0:c0 + FC].astype(np.float64)
    return np.stack([(h > 0).astype(np.float64), h / 30, np.minimum(5, np.maximum(-2, d / 10))]).astype(np.float32)


def context(buildings, origin, from_deg, cs, ct):
    """Context around the window centre (cs, ct) on a 6 m grid: 100 rows (+-300 m across) x 88 columns (435 m upwind to
    93 m downwind). Channels: built fraction, mean height of the built part / 30 m, maximum height / 30 m, pooled 4 x 4
    from a 1.5 m raster."""
    k = CTX_SUB
    H, _ = raster(buildings, origin, from_deg, CTX_S0 + cs, CTX_T0 + ct, CTX_ALONG * k, CTX_ACROSS * k,
                  step=CTX_STEP / k, heights_only=True)
    b = H.reshape(CTX_ACROSS, k, CTX_ALONG, k).transpose(0, 2, 1, 3).reshape(CTX_ACROSS, CTX_ALONG, k * k)
    b = b.astype(np.float64)
    n = (b > 0).sum(-1)
    mean = np.where(n > 0, np.where(b > 0, b, 0).sum(-1) / np.maximum(n, 1), 0) / 30
    return np.stack([n / (k * k), mean, b.max(-1) / 30]).astype(np.float32)


def _row(a, b):
    """Windows along one axis: the fewest (up to KMAX) that cover [a, b] with a margin; centres on a 60 m grid."""
    if not math.isfinite(a):
        return 0.0, 1, False
    a, b = a - MARGIN, b + MARGIN
    half = SPACING / 2
    for n in range(1, KMAX + 1):
        if (n - 1) * SPACING + WIN < b - a:
            continue
        ideal = (a + b) / 2 - (n - 1) * SPACING / 2
        for p0 in sorted([math.floor(ideal / half) * half, math.ceil(ideal / half) * half], key=lambda x: abs(x - ideal)):
            if p0 - WIN / 2 <= a and p0 + (n - 1) * SPACING + WIN / 2 >= b:
                return p0, n, False
    return _round_half_up(((a + b) / 2 - (KMAX - 1) * SPACING / 2) / half) * half, KMAX, True


def _round_half_up(x):
    return math.floor(x + 0.5)


def _taper(i):
    return np.minimum(1.0, np.minimum((i + 0.5) / TAPER, (NW - i - 0.5) / TAPER))


def predict(session, buildings, origin=(0.0, 0.0), from_deg=270.0):
    """K over the site: windows of 150 m on a 120 m grid around the buildings, frame and mirror averaged, windows blended
    with weights falling towards their edges. Returns dict with K [nt, ns] (NaN outside windows), solid mask, the grid
    origin in wind axes (s0, t0) and cell-centre coordinates x, y in scene metres."""
    ax, ay = wind_axes(from_deg)
    g = _ground(buildings)
    st = [((x - origin[0]) * ax[0] + (y - origin[1]) * ax[1], (x - origin[0]) * ay[0] + (y - origin[1]) * ay[1])
          for b in g for x, y in b["footprint"]]
    smin = min((s for s, _ in st), default=math.inf); smax = max((s for s, _ in st), default=-math.inf)
    tmin = min((t for _, t in st), default=math.inf); tmax = max((t for _, t in st), default=-math.inf)
    ps, ns_, clip_s = _row(smin, smax)
    pt, nt_, clip_t = _row(tmin, tmax)
    step_c = int(SPACING / STEP)
    out_s0, out_t0 = ps - WIN / 2, pt - WIN / 2
    out_ns, out_nt = (ns_ - 1) * step_c + NW, (nt_ - 1) * step_c + NW
    in_ns, in_nt = (ns_ - 1) * step_c + FC, (nt_ - 1) * step_c + FR
    H, sdf = raster(g, origin, from_deg, out_s0 - UP, out_t0 - SIDE, in_ns, in_nt)
    w1 = _taper(np.arange(NW))
    w = w1[:, None] * w1[None, :]
    num = np.zeros((out_nt, out_ns)); den = np.zeros((out_nt, out_ns))
    for kt in range(nt_):
        for ks in range(ns_):
            r0, c0 = kt * step_c, ks * step_c
            f = frame_channels(H, sdf, r0, c0)
            c = context(g, origin, from_deg, out_s0 + ks * SPACING + WIN / 2, out_t0 + kt * SPACING + WIN / 2)
            frames = np.ascontiguousarray(np.stack([f, f[:, ::-1, :]]))
            ctx = np.ascontiguousarray(np.stack([c, c[:, ::-1, :]]))
            k = session.run(["k_ped"], {"frames": frames, "ctx": ctx})[0]
            k = (0.5 * (k[0].astype(np.float64) + k[1][::-1, :].astype(np.float64))).astype(np.float32)
            num[r0:r0 + NW, c0:c0 + NW] += w * k[ROW0:ROW0 + NW, COL0:COL0 + NW]
            den[r0:r0 + NW, c0:c0 + NW] += w
    K = np.where(den > 0, num / np.where(den > 0, den, 1), np.nan).astype(np.float32)
    solid = H[ROW0:ROW0 + out_nt, COL0:COL0 + out_ns] > 0
    s = out_s0 + (np.arange(out_ns) + 0.5) * STEP
    t = out_t0 + (np.arange(out_nt) + 0.5) * STEP
    S, T = np.meshgrid(s, t)
    return {"K": K, "solid": solid, "s0": out_s0, "t0": out_t0, "windows": ns_ * nt_, "clipped": clip_s or clip_t,
            "x": origin[0] + S * ax[0] + T * ay[0], "y": origin[1] + S * ax[1] + T * ay[1]}


def demo_buildings():
    box = lambda x0, x1, y0, y1, h: {"footprint": [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], "height": h}
    blocks = [box(i * 40 - 12, i * 40 + 12, j * 45 - 15, j * 45 + 15, 12 + 6 * ((i + j + 10) % 4))
              for i in range(-3, 4) for j in range(-2, 3)]
    return blocks + [box(-300, -260, -20, 20, 60)]


if __name__ == "__main__":
    import onnxruntime as ort
    if len(sys.argv) < 2:
        raise SystemExit("python sreda_ml_example.py model.onnx [wind_from_deg] [U10 m/s]")
    sess = ort.InferenceSession(sys.argv[1], providers=["CPUExecutionProvider"])
    wind_from = float(sys.argv[2]) if len(sys.argv) > 2 else 270.0
    u10 = float(sys.argv[3]) if len(sys.argv) > 3 else 5.0
    r = predict(sess, demo_buildings(), (0.0, 0.0), wind_from)
    K = np.where(r["solid"], np.nan, r["K"])
    speed = K * U_IN_PED * u10
    print(f"windows {r['windows']}, grid {K.shape[0]} x {K.shape[1]} cells of {STEP} m")
    print(f"K at 1.75 m: min {np.nanmin(K):.3f}, mean {np.nanmean(K):.3f}, max {np.nanmax(K):.3f}")
    print(f"speed at 1.75 m for U10 = {u10} m/s: mean {np.nanmean(speed):.2f} m/s, max {np.nanmax(speed):.2f} m/s")
    np.savez_compressed("sreda_ml_demo.npz", K=r["K"], solid=r["solid"], x=r["x"], y=r["y"])
    print("saved sreda_ml_demo.npz (K, solid, x, y)")