Spaces:
Running
Running
Download session-08.html from hydros-ou/dcrest-course: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/spaces/hydros-ou/dcrest-course/resolve/main/session-08.html
- Command line
-
hf download hf://spaces/hydros-ou/dcrest-course/session-08.html
-
curl -L -o session-08.html https://huggingface.co/spaces/hydros-ou/dcrest-course/resolve/main/session-08.html
20.1 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>Session 8 · Routing: reservoir and unit hydrograph — dCREST, step by step</title> | |
| <meta name="description" content="How dCREST delays overland flow in a fast reservoir, removes a loss fraction, and spreads each day's runoff over the following days with a gamma unit hydrograph."> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,600;1,6..72,400&family=Source+Sans+3:wght@400;600;700&display=swap"> | |
| <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"> | |
| <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uplot@1.6.31/dist/uPlot.min.css"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css"> | |
| <link rel="stylesheet" href="assets/course.css"> | |
| <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script> | |
| <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"></script> | |
| <script defer src="https://cdn.jsdelivr.net/npm/uplot@1.6.31/dist/uPlot.iife.min.js"></script> | |
| <script defer src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script> | |
| <script defer src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script> | |
| <script defer src="assets/dcrest.js"></script> | |
| <script defer src="assets/course.js"></script> | |
| </head> | |
| <body> | |
| <main> | |
| <div class="kicker">Session 8 · Inside one day</div> | |
| <h1>Routing: reservoir and unit hydrograph</h1> | |
| <p class="lede">The soil and the aquifer decide how much water leaves the land each day. Routing decides <em>when</em> it passes the gauge. Water generated in the far corners of the Leaf River's 1924 km² needs days to travel down the channels, so a storm's runoff arrives spread out over the following week. This session covers the three steps that do this: the fast reservoir, the loss fraction and the unit hydrograph.</p> | |
| <div class="meta"><span><b>Time</b> about 30 minutes</span><span><b>Needs</b> Sessions 5–7</span></div> | |
| <figure class="video"><video controls preload="none" playsinline poster="video/s08.jpg"><source src="video/s08.mp4" type="video/mp4"></video> | |
| <figcaption>Watch this session first: a 6-minute narrated video with English subtitles. The page below goes further and lets you try each step yourself.</figcaption></figure> | |
| <div class="goals"><h4>You will be able to</h4><ul> | |
| <li>step the fast reservoir and say what <var data-v="qc">qc</var> does;</li> | |
| <li>explain the loss fraction <var data-v="lf">lf</var>;</li> | |
| <li>build the gamma unit hydrograph from <var data-v="nshape">nshape</var>, <var data-v="kmult">kmult</var> and the catchment area;</li> | |
| <li>compute river flow as a convolution of daily runoff with the unit hydrograph.</li> | |
| </ul></div> | |
| <figure class="wide"><div class="plate"><svg id="map" role="img" aria-label="Model diagram with routing highlighted"></svg></div> | |
| <figcaption>Where we are: the end of the chain, from the three runoff paths to the river flow at the gauge.</figcaption></figure> | |
| <h2>The fast reservoir</h2> | |
| <p>Overland flow from the soil step (Session 6) first enters a store, the fast reservoir, holding <var data-v="Fs">F<sub>s</sub></var> mm. Each day it releases a fixed fraction <var data-v="qc">qc</var> of what it holds:</p> | |
| <div class="eq">\[ F_s \leftarrow F_s + Q_{\text{ov}}, \qquad Q_r = \min(\mathit{qc},\, 1)\cdot F_s, \qquad F_s \leftarrow F_s - Q_r \]</div> | |
| <p>This is the linear reservoir of Session 2. For the Leaf River <var>qc</var> = 0.659 per day: 66% of a day's overland flow leaves the same day, 22% the next day and 8% the day after. The minimum guards against releasing more than the store holds, which could only happen with a time step longer than a day.</p> | |
| <h2>Losses</h2> | |
| <p>The three outflows are added up and a fixed fraction <var data-v="lf">lf</var> is removed:</p> | |
| <div class="eq">\[ r = \big(Q_r + Q_{\text{int}} + Q_b + Q_{sp}\big)\,(1 - \mathit{lf}) \]</div> | |
| <p>\(r\) is the day's runoff, ready to be routed to the gauge. The loss represents water that leaves the catchment without passing the gauge, such as deep groundwater flowing under the river or water withdrawn for use. Like other parameters it is effective. It also absorbs systematic errors in the forcing, for example rainfall estimates that are slightly too high. For the Leaf River <var>lf</var> = 0.108: about 11% of runoff, 60 mm per year over 1989–1999, is removed.</p> | |
| <h2>The unit hydrograph</h2> | |
| <p>Suppose 10 mm of runoff is generated across the catchment on one day. Water produced next to the gauge passes it within hours; water from the headwaters takes days. The share of the day's runoff that passes the gauge 0, 1, 2, … days later is the catchment's <strong>unit hydrograph</strong>: the river's response to one unit of runoff. dCREST uses a gamma distribution for it, a curve that rises quickly and then decays slowly:</p> | |
| <div class="eq">\[ w_i \;\propto\; \frac{1}{\Gamma(n)} \left[\frac{(i + \tfrac12)\,\Delta t}{k}\right]^{n-1} \exp\!\left[-\frac{(i + \tfrac12)\,\Delta t}{k}\right], \qquad i = 0, 1, \dots, 29, \qquad \sum_i w_i = 1 \]</div> | |
| <p class="eqnote">\(w_i\): share of a day's runoff passing the gauge \(i\) days later. \(\Delta t\) = 24 h. Each day is represented by its midpoint, \(i + \tfrac12\). The weights are normalised to sum to exactly 1, so no water is lost or gained.</p> | |
| <p>The shape is set by \(n\) = <var data-v="nshape">nshape</var>: for the same time scale, larger values give a later and broader response (and a more symmetric one). The time scale \(k\) (hours) comes from the catchment's size, scaled by <var data-v="kmult">kmult</var>:</p> | |
| <div class="eq">\[ k_g = 0.35 \left(\frac{A}{1000\ \text{km}^2}\right)^{0.38} \times 24\ \text{h}, \qquad k = \max(\mathit{kmult}\cdot k_g,\; 1\ \text{h}) \]</div> | |
| <p>\(k_g\) is a rule of thumb: larger catchments respond more slowly, roughly with area to the power 0.38. It makes <var>kmult</var> a dimensionless correction that can be compared between catchments of different sizes. For the Leaf River, \(A\) = 1924 km² gives \(k_g\) = 10.8 h. With <var>kmult</var> = 1.83, \(k\) = 19.7 h and, with \(n\) = 2.74, the weights are:</p> | |
| <div class="tablewrap"><table> | |
| <thead><tr><th>days after</th><th class="n">0</th><th class="n">1</th><th class="n">2</th><th class="n">3</th><th class="n">4</th><th class="n">5</th><th class="n">6</th><th class="n">7</th></tr></thead> | |
| <tbody><tr><td>share \(w_i\)</td><td class="n">17.3%</td><td class="n">34.6%</td><td class="n">24.8%</td><td class="n">13.1%</td><td class="n">6.0%</td><td class="n">2.5%</td><td class="n">1.0%</td><td class="n">0.4%</td></tr></tbody></table></div> | |
| <p>So the peak of a storm's runoff passes the gauge the day after it is generated, and most has passed within four days.</p> | |
| <div class="callout warn"><span class="label">A floor that once broke calibration</span> | |
| <p>\(k\) has a floor: it cannot be shorter than 1 hour. An earlier version set the floor at half a day. Because \(\mathit{kmult}\cdot k_g\) is shorter than 12 hours in most CAMELS catchments, the floor was active almost everywhere, and <var>kmult</var> had no effect at all on the result: the model could not be calibrated in that parameter, yet nothing in the scores showed it. The gradients exposed it (Session 12), and v1.0 lowered the floor to 1 hour.</p> | |
| </div> | |
| <h2>River flow is a convolution</h2> | |
| <p>Each day's runoff is spread over the following days by the same weights, and the river flow on any day is the sum of the shares arriving from all earlier days:</p> | |
| <div class="eq">\[ Q_t \;=\; \sum_{i=0}^{29} w_i\, r_{t-i} \]</div> | |
| <p>This operation is called a <strong>convolution</strong>. Step through it below on the days around the 27 August 1992 storm.</p> | |
| <div class="widget wide" id="cv"> | |
| <div class="whead"><span class="wtag">Try it</span><span class="wtitle">Convolution, one day at a time</span></div> | |
| <div class="btnrow"><button class="btn ghost" id="cv_prev" type="button">◂ day before</button><button class="btn" id="cv_next" type="button">next day ▸</button><button class="btn ghost" id="cv_play" type="button">play</button><span class="note" id="cv_lab"></span></div> | |
| <svg id="cv_svg" viewBox="0 0 900 300" role="img" aria-label="Bars of daily runoff, each spread over the following days, summing to river flow"></svg> | |
| <p class="note">Faint blue bars: daily runoff \(r\) from the model. Each coloured band is one day's runoff spread over the following days by the weights \(w_i\); grey at the bottom is runoff from days before the window that is still arriving. The dark line is their sum, the routed flow \(Q\), and the dots are the observed flow.</p> | |
| </div> | |
| <h2>Shape the response</h2> | |
| <div class="widget wide" id="uh"> | |
| <div class="whead"><span class="wtag">Try it</span><span class="wtitle">Unit-hydrograph shape and the February 1990 flood</span></div> | |
| <div class="controls" id="uh_ctl"></div> | |
| <div class="grid2" style="margin:0"> | |
| <div><div class="note">Weights \(w_i\) (share of a day's runoff arriving \(i\) days later)</div><div class="chart" id="uh_w"></div></div> | |
| <div><div class="note">The flood of February 1990, routed with these weights</div><div class="chart" id="uh_q"></div></div> | |
| </div> | |
| <p class="stats" id="uh_stats"></p> | |
| <p class="note">Only the routing changes here; the runoff \(r\) is the same. A shorter time scale sharpens the peak and moves it earlier; a larger <var>nshape</var> delays it. The runoff entering the routing, \(r\), peaked at about 68 mm on 16 February, one day before the observed peak. Routing that sharply would put the model's peak a day early; the calibrated weights put it on the right day, but lower. Calibration has to balance the timing and the height of every flood in the record, not only this one.</p> | |
| </div> | |
| <div class="callout code"><span class="label">In the code: src/dcrest/routing/uh.py and model.py</span> | |
| <pre><code>def gamma_uh(nshape, kscale_h, *, nstep=30, dt_hours=24.0, kmin_h=None, eps=1e-6): | |
| n = torch.clamp(nshape, min=0.5, max=12.0) | |
| kmin = dt_hours * 0.5 if kmin_h is None else kmin_h # the old floor was dt / 2 | |
| k = torch.clamp(kscale_h, min=kmin) | |
| t = (torch.arange(nstep, dtype=n.dtype, device=n.device) + 0.5) * dt_hours | |
| tt = t[:, None] / k[None, :] | |
| logw = (n[None, :] - 1.0) * torch.log(tt + eps) - tt - torch.lgamma(n[None, :]) | |
| w = torch.exp(logw) | |
| return w / torch.clamp(w.sum(0, keepdim=True), min=eps) | |
| # model.py, after the daily loop has produced runoff for every day: | |
| weights = gamma_uh(params["nshape"], lag * params["kmult"], nstep=cfg.uh_nstep, | |
| dt_hours=cfg.dt_hours, kmin_h=cfg.uh_kmin_h) | |
| discharge = convolve_uh(runoff, weights)</code></pre> | |
| <p>Routing comes <em>after</em> the daily loop, because it does not feed back into any store. The whole runoff series is convolved in one pass, which on a GPU is a single grouped convolution over all catchments. The weights are computed in log space for numerical safety.</p> | |
| </div> | |
| <h2>In Python</h2> | |
| <div class="pycell" data-title="A unit hydrograph and a convolution"> | |
| <textarea> | |
| from dcrest_course import * | |
| case = load_case() | |
| p = case.params | |
| kg = lag_hours(case.area_km2) | |
| k = max(p["kmult"] * kg, 1.0) | |
| w = gamma_uh(p["nshape"], p["kmult"], case.area_km2) | |
| print(f"area {case.area_km2:.0f} km2 -> k_g = {kg:.1f} h; k = kmult * k_g = {k:.1f} h; n = {p['nshape']:.2f}") | |
| print("weights for days 0-7:", np.round(w[:8], 3), " sum of all 30:", w.sum()) | |
| r = np.zeros(40); r[2] = 10.0 # one day with 10 mm of runoff (40 days, so the whole tail fits) | |
| Q = convolve(r, w) | |
| for t in range(10): | |
| print(f"day {t:2d}: runoff {r[t]:5.1f} -> flow {Q[t]:6.3f}") | |
| print("total flow out:", Q.sum().round(6), "mm (all 10 mm arrive, spread over days)") | |
| plot(np.arange(15), r[:15], Q[:15], labels=["runoff r", "river flow Q"], title="One day of runoff, routed", xlabel="day", kind="bar") | |
| </textarea> | |
| </div> | |
| <h2>Check your understanding</h2> | |
| <div class="quiz"> | |
| <details><summary>The fast reservoir holds 4 mm, receives 6 mm of overland flow, and <var>qc</var> = 0.5. What is released and what remains?</summary><div class="ans"><p>It first holds 10 mm, releases \(0.5 \times 10 = 5\) mm, and keeps 5 mm.</p></div></details> | |
| <details><summary>Runoff is 10 mm today and zero on all other days. With the Leaf River's weights, what is the river flow tomorrow?</summary><div class="ans"><p>\(10 \times w_1 \approx 10 \times 0.346 \approx 3.5\) mm/day.</p></div></details> | |
| <details><summary>Why does a larger catchment get a larger time scale \(k_g\)?</summary><div class="ans"><p>Water has further to travel to the outlet, so the response is slower and more spread out. The rule \(k_g \propto A^{0.38}\) captures this on average.</p></div></details> | |
| <details><summary>Can the unit hydrograph create or destroy water?</summary><div class="ans"><p>No. The weights sum to 1, so every millimetre of runoff eventually passes the gauge; routing only changes when. (Water still "in transit" at the end of a simulation has not yet arrived.)</p></div></details> | |
| </div> | |
| <div class="remember"><h4>What to remember</h4><ul> | |
| <li>Overland flow is delayed by a linear reservoir releasing a fraction <var>qc</var> per day.</li> | |
| <li>The three outflows are summed and reduced by the loss fraction <var>lf</var>.</li> | |
| <li>A gamma unit hydrograph with shape <var>nshape</var> and time scale \(\max(\mathit{kmult}\cdot k_g, 1\ \text{h})\) spreads each day's runoff over 30 days: the same day and the 29 after it.</li> | |
| <li>River flow is the convolution \(Q_t = \sum_i w_i r_{t-i}\), computed once after the daily loop.</li> | |
| </ul></div> | |
| </main> | |
| <script> | |
| window.pageInit = async function () { | |
| Course.modelDiagram(document.getElementById("map"), { highlight: "route" }); | |
| const c = await Course.data(), css = Course.css; | |
| const run = c.protocolRun("test", null, true), R = run.rec, w = run.uh.w; | |
| // ---- convolution stepper around the 1992 storm | |
| const a0 = c.idx("1992-08-22") - run.i0, NDAYS = 20; | |
| let cur = 5; | |
| const svg = document.getElementById("cv_svg"); | |
| const palette = ["--fast", "--snow", "--aquifer", "--et", "--inter", "--canopy", "--soil", "--accent"].map(css); | |
| function drawCv() { | |
| const r = R.r.subarray(a0, a0 + NDAYS), q = run.Q.subarray(a0, a0 + NDAYS), o = run.obs.subarray(a0, a0 + NDAYS); | |
| const X0 = 50, X1 = 880, Y0 = 250, Y1 = 20, bw = (X1 - X0) / NDAYS; | |
| const ymax = Math.max(...r, ...q, ...o) * 1.08; | |
| const y = (v) => Y0 - (v / ymax) * (Y0 - Y1); | |
| let h = ""; | |
| for (let v = 0; v <= ymax; v += 5) h += `<line x1="${X0}" y1="${y(v)}" x2="${X1}" y2="${y(v)}" stroke="${css("--rule")}"/><text x="${X0 - 8}" y="${y(v) + 4}" text-anchor="end" font-size="12">${v}</text>`; | |
| for (let d = 0; d < NDAYS; d++) h += `<rect x="${X0 + d * bw + 3}" y="${y(r[d])}" width="${bw - 6}" height="${Y0 - y(r[d])}" fill="${css("--snow")}" opacity="0.25"/>`; | |
| // stacked contributions to each day up to 'cur' | |
| for (let d = 0; d <= cur; d++) { | |
| let inWin = 0; | |
| for (let s = Math.max(0, d - 29); s <= d; s++) inWin += w[d - s] * r[s]; | |
| let base = Math.max(q[d] - inWin, 0); // runoff from days before the window, still arriving | |
| if (base > 1e-3) h += `<rect x="${X0 + d * bw + 8}" y="${y(base)}" width="${bw - 16}" height="${Y0 - y(base)}" fill="${css("--faint")}" opacity="0.9"/>`; | |
| for (let s = Math.max(0, d - 29); s <= d; s++) { | |
| if (s < 0) continue; | |
| const part = w[d - s] * r[s]; | |
| if (part < 1e-3) { base += part; continue; } | |
| const col = palette[s % palette.length]; | |
| h += `<rect x="${X0 + d * bw + 8}" y="${y(base + part)}" width="${bw - 16}" height="${y(base) - y(base + part)}" fill="${col}" opacity="0.85"/>`; | |
| base += part; | |
| } | |
| } | |
| h += `<polyline fill="none" stroke="${css("--ink")}" stroke-width="2" points="${Array.from(q.subarray(0, cur + 1), (v, d) => `${X0 + d * bw + bw / 2},${y(v)}`).join(" ")}"/>`; | |
| for (let d = 0; d <= cur; d++) h += `<circle cx="${X0 + d * bw + bw / 2}" cy="${y(o[d])}" r="3.5" fill="${css("--obs")}"/>`; | |
| for (let d = 0; d < NDAYS; d += 2) h += `<text x="${X0 + d * bw + bw / 2}" y="${Y0 + 18}" text-anchor="middle" font-size="11.5">${c.iso(run.i0 + a0 + d).slice(5)}</text>`; | |
| h += `<line x1="${X0 + cur * bw + bw / 2}" y1="${Y1}" x2="${X0 + cur * bw + bw / 2}" y2="${Y0}" stroke="${css("--accent")}" stroke-dasharray="3 3"/>`; | |
| svg.innerHTML = h + `<text x="${X0}" y="${Y0 + 40}" font-size="12">mm/day</text>`; | |
| const parts = []; | |
| for (let s = Math.max(0, cur - 29); s <= cur; s++) { const v = w[cur - s] * r[s]; if (v > 0.01) parts.push(`${w[cur - s].toFixed(3)}×${r[s].toFixed(1)}`); } | |
| document.getElementById("cv_lab").textContent = `${c.iso(run.i0 + a0 + cur)}: Q = ${parts.slice(-4).join(" + ")}${parts.length > 4 ? " + …" : ""} + earlier days = ${q[cur].toFixed(2)} mm/day (observed ${o[cur].toFixed(2)})`; | |
| } | |
| document.getElementById("cv_prev").addEventListener("click", () => { cur = Math.max(0, cur - 1); drawCv(); }); | |
| document.getElementById("cv_next").addEventListener("click", () => { cur = Math.min(NDAYS - 1, cur + 1); drawCv(); }); | |
| let timer = null; | |
| document.getElementById("cv_play").addEventListener("click", (e) => { | |
| if (timer) { clearInterval(timer); timer = null; e.target.textContent = "play"; return; } | |
| e.target.textContent = "pause"; cur = 0; | |
| timer = setInterval(() => { drawCv(); cur++; if (cur >= NDAYS) { clearInterval(timer); timer = null; e.target.textContent = "play"; cur = NDAYS - 1; } }, 650); | |
| }); | |
| drawCv(); | |
| // ---- UH shape and the 1990 flood | |
| const st = { n: c.params.nshape, km: c.params.kmult }; | |
| const a1 = c.idx("1990-02-05") - run.i0, b1 = c.idx("1990-03-10") - run.i0 + 1, t1 = run.time.subarray(a1, b1); | |
| let uw = null, uq = null; | |
| function drawUh() { | |
| const uh = DCREST.gammaUH(st.n, st.km, c.area_km2); | |
| const Q = DCREST.convolve(R.r, uh.w); | |
| const x = Float64Array.from({ length: 12 }, (_, i) => i); | |
| const ws = uh.w.subarray(0, 12); | |
| if (uw) uw.setData([x, ws]); else uw = Course.xyChart(document.getElementById("uh_w"), { x, height: 230, xlabel: "days after", ylabel: "share", xint: true, | |
| series: [{ label: "w_i", values: ws, color: css("--accent"), bars: true }] }); | |
| const d = [t1, run.obs.subarray(a1, b1), Q.subarray(a1, b1), R.r.subarray(a1, b1)]; | |
| if (uq) uq.setData(d); else uq = Course.tsChart(document.getElementById("uh_q"), { time: t1, height: 230, ylabel: "mm/day", | |
| series: [{ label: "observed", values: d[1], color: css("--obs") }, { label: "routed Q", values: d[2], color: css("--sim"), width: 2 }, | |
| { label: "runoff r (before routing)", values: d[3], color: css("--fast"), dash: [4, 3] }] }); | |
| let peak = 0; for (let i = a1; i < b1; i++) peak = Math.max(peak, Q[i]); | |
| document.getElementById("uh_stats").innerHTML = `<span class="s"><span class="k">time scale k</span><span class="v2">${uh.k.toFixed(1)} h</span></span> | |
| <span class="s"><span class="k">average delay Σ i·wᵢ</span><span class="v2">${uh.w.reduce((a, v, i) => a + i * v, 0).toFixed(2)} days</span></span> | |
| <span class="s"><span class="k">routed peak, Feb 1990</span><span class="v2">${peak.toFixed(1)} mm/day</span></span>`; | |
| } | |
| const ctl = document.getElementById("uh_ctl"); | |
| Course.slider(ctl, { label: "shape nshape", min: c.bounds.nshape[0], max: c.bounds.nshape[1], step: 0.01, value: st.n, fmt: (v) => v.toFixed(2) }, (v) => { st.n = v; drawUh(); }); | |
| Course.slider(ctl, { label: "time-scale multiplier kmult", min: c.bounds.kmult[0], max: c.bounds.kmult[1], step: 0.01, value: st.km, fmt: (v) => v.toFixed(2) }, (v) => { st.km = v; drawUh(); }); | |
| drawUh(); | |
| }; | |
| </script> | |
| </body> | |
| </html> | |