-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdash_app.py
More file actions
792 lines (711 loc) · 38 KB
/
Copy pathdash_app.py
File metadata and controls
792 lines (711 loc) · 38 KB
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
"""Plotly Dash interface for the HydRun rainfall-runoff workflow."""
from __future__ import annotations
import base64
import csv
import io
from datetime import date, datetime, timedelta
from pathlib import Path
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from dash import Dash, Input, Output, State, ctx, dash_table, dcc, html, no_update
from hydrun_functions import (
TIME_CHARACTERISTIC_NAMES, compute_antecedent_precipitation,
compute_initial_abstraction, compute_recession_constant,
compute_runoff_ratio, compute_time_characteristics,
extract_precipitation_events, extract_runoff, generalize_recession,
match_rainfall_runoff, separate_baseflow,
)
ROOT = Path(__file__).resolve().parent
STATE = {}
def mat_datetime(value):
whole = int(value)
seconds = round((float(value) - whole) * 86400)
return datetime.fromordinal(whole) + timedelta(seconds=seconds, days=-366)
def plot_dates(values):
return [mat_datetime(value) for value in values]
def date_number(value):
value = date.fromisoformat(value) if isinstance(value, str) else value
return float(value.toordinal() + 366)
def format_boundary_time(step):
return mat_datetime(STATE["stormflow"][int(step), 0]).strftime("%m-%d %H:%M")
def boundary_time_to_step(value, event_index=None):
"""Map an entered timestamp to the nearest available stormflow record."""
if value is None or not str(value).strip():
raise ValueError("Enter both start and end times.")
try:
partial = datetime.strptime(str(value).strip(), "%m-%d %H:%M")
except ValueError as error:
raise ValueError("Use timestamp format MM-DD HH:MM.") from error
if event_index is not None and STATE.get("runoff_events"):
event = STATE["runoff_events"][int(event_index)]
reference = mat_datetime(event[len(event) // 2, 0])
else:
reference = mat_datetime(STATE["stormflow"][0, 0])
candidates = [
partial.replace(year=year)
for year in (reference.year - 1, reference.year, reference.year + 1)
]
entered = min(candidates, key=lambda candidate: abs(candidate - reference))
matlab_value = entered.toordinal() + 366 + (
entered.hour * 3600 + entered.minute * 60 + entered.second
) / 86400
return int(np.argmin(np.abs(STATE["stormflow"][:, 0] - matlab_value)))
def shift_boundary_time(value, change, event_index=None):
step = boundary_time_to_step(value, event_index)
step = max(0, min(step + int(change), len(STATE["stormflow"]) - 1))
return format_boundary_time(step)
def load_csv_series(source, series_name):
"""Read timestamp/value CSV data and convert timestamps to MATLAB dates."""
if isinstance(source, (str, Path)):
handle = open(source, newline="", encoding="utf-8-sig")
close_handle = True
else:
handle, close_handle = source, False
try:
reader = csv.reader(handle)
header = next(reader, None)
if header is None or len(header) != 2:
raise ValueError(
f"{series_name} CSV must have exactly two columns: timestamp and value.")
records = []
for row_number, row in enumerate(reader, 2):
if not row or all(not item.strip() for item in row):
continue
if len(row) != 2:
raise ValueError(f"{series_name} CSV row {row_number} does not have two columns.")
try:
timestamp = datetime.fromisoformat(row[0].strip())
value = float(row[1]) if row[1].strip() else np.nan
except ValueError as error:
raise ValueError(
f"Invalid {series_name} data on CSV row {row_number}: {error}") from error
serial_date = timestamp.toordinal() + 366 + (
timestamp.hour * 3600 + timestamp.minute * 60 +
timestamp.second + timestamp.microsecond / 1_000_000
) / 86400
records.append((serial_date, value))
finally:
if close_handle:
handle.close()
array = np.asarray(records, dtype=float)
if array.ndim != 2 or array.shape[1] != 2 or len(array) < 2:
raise ValueError(f"{series_name} CSV must contain at least two data rows.")
if np.any(np.diff(array[:, 0]) <= 0):
raise ValueError(f"{series_name} timestamps must be strictly increasing.")
return array
def decode_uploaded_csv(contents, series_name):
_, payload = contents.split(",", 1)
text = base64.b64decode(payload).decode("utf-8-sig")
return load_csv_series(io.StringIO(text), series_name)
def reset(flow, rain):
STATE.clear()
STATE.update(streamflow=flow, precipitation=rain)
def blank(text):
figure = go.Figure()
figure.add_annotation(text=text, x=.5, y=.5, xref="paper", yref="paper",
showarrow=False, font={"size": 16, "color": "#64748b"})
figure.update_layout(template="plotly_white", xaxis={"visible": False},
yaxis={"visible": False}, margin=dict(l=20, r=20, t=25, b=20))
return figure
def summary_column(title, data, unit):
values = data[:, 1]
valid = values[np.isfinite(values)]
step = np.median(np.diff(data[:, 0])) * 1440
entries = [
title, f"Start: {mat_datetime(data[0, 0]):%Y-%m-%d}",
f"End: {mat_datetime(data[-1, 0]):%Y-%m-%d}",
f"Period: {data[-1, 0] - data[0, 0]:.1f} days",
f"Time step: {step:.1f} min", f"Minimum: {valid.min():.4g} {unit}",
f"Median: {np.median(valid):.4g} {unit}",
f"Average: {valid.mean():.4g} {unit}",
f"95% quantile: {np.quantile(valid, .95):.4g} {unit}",
f"Maximum: {valid.max():.4g} {unit}",
f"Missing values: {np.isnan(values).sum()}",
]
return html.Div([html.Strong(entries[0]), *[html.Span(x) for x in entries[1:]]],
className="summary-column")
def summary(flow, rain):
return html.Div([summary_column("Streamflow", flow, "m³/s"),
summary_column("Precipitation", rain, "mm")],
className="summary-grid")
def baseflow_plot(flow, base):
fig = go.Figure()
fig.add_scatter(x=plot_dates(flow[:, 0]), y=flow[:, 1], name="Streamflow",
mode="lines", line=dict(color="#2563eb", width=1))
fig.add_scatter(x=plot_dates(base[:, 0]), y=base[:, 1], name="Baseflow",
mode="lines", line=dict(color="#ef4444", width=1.5))
return style_plot(fig, "Baseflow hydrograph", "Discharge (m³/s)")
def runoff_plot(background, events, label):
fig = go.Figure()
fig.add_scatter(x=plot_dates(background[:, 0]), y=background[:, 1], name=label,
mode="lines", line=dict(color="#2563eb", width=1))
for i, event in enumerate(events):
fig.add_scatter(x=plot_dates(event[:, 0]), y=event[:, 1], mode="lines",
name="Runoff events", legendgroup="events", showlegend=i == 0,
line=dict(color="#16a34a", width=2),
customdata=np.full((len(event), 1), i + 1),
hovertemplate="Event %{customdata[0]}<br>%{x}<br>%{y:.4g}<extra></extra>")
if events:
event_numbers = np.arange(1, len(events) + 1)
fig.add_scatter(
x=[mat_datetime(event[0, 0]) for event in events],
y=[event[0, 1] for event in events],
mode="markers", name="Event start",
marker=dict(color="#2563eb", size=8, line=dict(color="white", width=1)),
customdata=event_numbers,
hovertemplate="Event %{customdata} start<br>%{x}<br>%{y:.4g}<extra></extra>",
)
fig.add_scatter(
x=[mat_datetime(event[-1, 0]) for event in events],
y=[event[-1, 1] for event in events],
mode="markers", name="Event end",
marker=dict(color="#dc2626", size=8, line=dict(color="white", width=1)),
customdata=event_numbers,
hovertemplate="Event %{customdata} end<br>%{x}<br>%{y:.4g}<extra></extra>",
)
return style_plot(fig, "Delineated runoff events", "Discharge (m³/s)")
def boundary_preview_plot(event_index, boundaries):
"""Preview a candidate event boundary without changing stored events."""
stormflow = STATE["stormflow"]
start, end = sorted((int(boundaries[0]), int(boundaries[1])))
start = max(0, min(start, len(stormflow) - 1))
end = max(start, min(end, len(stormflow) - 1))
padding = max(8, int(round(12 / (np.median(np.diff(stormflow[:, 0])) * 24))))
lower, upper = max(0, start - padding), min(len(stormflow) - 1, end + padding)
context = stormflow[lower:upper + 1]
candidate = stormflow[start:end + 1]
fig = go.Figure()
fig.add_scatter(x=plot_dates(context[:, 0]), y=context[:, 1], mode="lines",
name="Local stormflow", line=dict(color="#94a3b8", width=1.5))
fig.add_scatter(x=plot_dates(candidate[:, 0]), y=candidate[:, 1], mode="lines",
name="Selected event", line=dict(color="#16a34a", width=3))
fig.add_scatter(x=[mat_datetime(stormflow[start, 0])], y=[stormflow[start, 1]],
mode="markers", name="Event start",
marker=dict(color="#2563eb", size=11, line=dict(color="white", width=1.5)))
fig.add_scatter(x=[mat_datetime(stormflow[end, 0])], y=[stormflow[end, 1]],
mode="markers", name="Event end",
marker=dict(color="#dc2626", size=11, line=dict(color="white", width=1.5)))
fig.update_layout(
template="plotly_white", title=f"Event {int(event_index) + 1} boundary preview",
height=320, yaxis_title="Stormflow (m³/s)", hovermode="x unified",
legend=dict(orientation="v", x=1.02, xanchor="left", y=1, yanchor="top"),
margin=dict(l=50, r=165, t=50, b=35),
)
return fig
def style_plot(fig, title, ylabel):
fig.update_layout(template="plotly_white", title=title, yaxis_title=ylabel,
hovermode="x unified", legend=dict(orientation="h"),
margin=dict(l=55, r=20, t=48, b=35))
return fig
def pair_plot(index):
rain, runoff = STATE["pairs"][index]
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
row_heights=[.35, .65], vertical_spacing=.08)
if len(rain):
width = np.median(np.diff(rain[:, 0])) * 86400000 if len(rain) > 1 else 3600000
fig.add_bar(x=plot_dates(rain[:, 0]), y=rain[:, 1], width=width,
name="Precipitation", marker_color="#2563eb", row=1, col=1)
fig.add_scatter(x=plot_dates(runoff[:, 0]), y=runoff[:, 1], name="Runoff",
mode="lines", line=dict(color="#16a34a", width=2), row=2, col=1)
fig.update_yaxes(title_text="Rainfall (mm)", autorange="reversed", row=1, col=1)
fig.update_yaxes(title_text="Discharge (m³/s)", row=2, col=1)
fig.update_layout(template="plotly_white", title=f"Rainfall–runoff event {index + 1}",
height=470, hovermode="x unified", legend=dict(orientation="h"),
margin=dict(l=60, r=20, t=48, b=35))
return fig
def recession_plot(curve, limbs):
fig = go.Figure()
for i, limb in enumerate(limbs):
fig.add_scatter(x=limb[:, 0], y=limb[:, 1], mode="lines",
name="Individual recessions", legendgroup="limbs",
showlegend=i == 0, line=dict(color="rgba(100,116,139,.3)", width=1))
fig.add_scatter(x=curve[:, 0], y=curve[:, 1], mode="lines",
name="Master recession curve", line=dict(color="#2563eb", width=3))
fig = style_plot(fig, "Master recession curve", "Normalized discharge")
fig.update_xaxes(title="Hours")
fig.update_yaxes(range=[0, 1.05])
return fig
def number(component_id, value, step="any", minimum=None):
return dcc.Input(id=component_id, type="number", value=value, step=step,
min=minimum, className="number-input")
def field(label, control, note=""):
return html.Label([html.Span(label), control, html.Small(note)], className="field")
def boundary_time_field(label, input_id, minus_id, plus_id):
return html.Label([
html.Span(label),
html.Div([
html.Button("−", id=minus_id, type="button", className="time-step-button",
title="Move back one time step"),
dcc.Input(id=input_id, type="text", value="",
placeholder="MM-DD HH:MM", debounce=True),
html.Button("+", id=plus_id, type="button", className="time-step-button",
title="Move forward one time step"),
], className="time-stepper"),
html.Small(""),
], className="field")
def panel(title, children):
return html.Section([html.H2(title), *children], className="panel")
flow = load_csv_series(ROOT / "streamflow.csv", "Streamflow")
rain = load_csv_series(ROOT / "precipitation.csv", "Precipitation")
reset(flow, rain)
first_date = mat_datetime(max(flow[0, 0], rain[0, 0])).date()
last_date = mat_datetime(min(flow[-1, 0], rain[-1, 0])).date()
app = Dash(__name__, title="HydRun Dashboard")
server = app.server
app.layout = html.Div([
html.Header([html.Div([html.H1("HydRun"), html.P("Event-based rainfall–runoff analysis")]),
html.Span("Plotly Dash edition")], className="app-header"),
html.Main(dcc.Tabs(id="workflow-tabs", value="input-tab", className="workflow-tabs",
parent_className="tabs-shell", children=[
dcc.Tab(label="1 Input Data", value="input-tab", className="workflow-tab",
selected_className="workflow-tab--selected", children=[
html.Div([
panel("Input data", [
html.Div([
html.Div([
html.Strong("Streamflow CSV"),
dcc.Upload(
id="streamflow-upload", accept=".csv,text/csv",
className="upload",
children=html.Div(
["Drop file here or ", html.A("browse")])),
]),
html.Div([
html.Strong("Precipitation CSV"),
dcc.Upload(
id="precipitation-upload", accept=".csv,text/csv",
className="upload",
children=html.Div(
["Drop file here or ", html.A("browse")])),
]),
], className="csv-upload-grid"),
html.Div(
"Loaded bundled streamflow.csv and precipitation.csv",
id="file-status", className="status success"),
]),
panel("Data Summary", [
html.Div(summary(flow, rain), id="summary"),
]),
panel("Select Period", [
html.Div([
field("Start date", dcc.DatePickerSingle(
id="start-date", date=first_date,
min_date_allowed=first_date,
max_date_allowed=last_date)),
field("End date", dcc.DatePickerSingle(
id="end-date", date=last_date,
min_date_allowed=first_date,
max_date_allowed=last_date)),
], className="two-columns"),
]),
], className="input-tab-content panel-stack"),
]),
dcc.Tab(label="2 Baseflow", value="baseflow-tab", className="workflow-tab",
selected_className="workflow-tab--selected", children=[
html.Div([
panel("Separate baseflow", [
html.Div([field("Filter coefficient", number("filter", .995, .001, 0)),
field("Passes", number("passes", 4, 1, 1))], className="two-columns"),
html.Button("Separate baseflow", id="base-button", className="primary"),
html.Div(id="base-status", className="status"),
]),
panel("Baseflow output", [
dcc.Loading(dcc.Graph(id="base-graph",
figure=blank("Separate baseflow to display results"))),
]),
], className="tab-workspace"),
]),
dcc.Tab(label="3 Runoff Events", value="runoff-tab", className="workflow-tab",
selected_className="workflow-tab--selected", children=[
html.Div([
panel("Extract runoff events", [
html.Div([
field("Peak threshold", number("threshold", .03, .01, 0)),
field("Return ratio", number("ratio", .1, .01, 0)),
field("Beginning slope", number("begin-slope", .001, .0001, 0)),
field("Ending slope", number("end-slope", .0001, .0001, 0)),
field("Smooth coefficient", number("smooth", 4, 1, 0)),
field("Minimum duration", number("duration", 0, 1, 0)),
], className="two-columns"),
field("Show events on", dcc.RadioItems(id="background", inline=True,
value="stormflow",
options=[{"label": "Streamflow", "value": "streamflow"},
{"label": "Baseflow-free", "value": "stormflow"}])),
html.Button("Extract runoff events", id="runoff-button",
className="primary"),
html.Div(id="runoff-status", className="status"),
]),
panel("Runoff-event output", [
dcc.Loading(dcc.Graph(id="runoff-graph",
figure=blank("Extract runoff events to display results"))),
]),
html.Div(
panel("Manual boundary adjustment", [
html.Div([
html.Div([
field("Event to edit", dcc.Dropdown(
id="boundary-event",
placeholder="Extract runoff events first")),
html.P(
"Move the two handles to set the event start and end "
"time steps.", className="field-note"),
dcc.RangeSlider(
id="boundary-slider", min=0, max=1, value=[0, 1],
step=1, marks={}, allowCross=False,
allow_direct_input=False,
className="boundary-slider"),
html.Div([
boundary_time_field(
"Start time", "boundary-start-step",
"start-time-minus", "start-time-plus"),
boundary_time_field(
"End time", "boundary-end-step",
"end-time-minus", "end-time-plus"),
], className="boundary-step-inputs"),
html.Button(
"Apply boundary adjustment", id="boundary-button",
className="secondary"),
html.Div(id="boundary-status", className="status"),
], className="boundary-controls"),
html.Div([
html.H3("Boundary preview"),
dcc.Loading(dcc.Graph(
id="boundary-preview",
figure=blank(
"Select an event to preview its boundaries"),
config={"displayModeBar": False},
className="boundary-preview",
)),
], className="boundary-preview-panel"),
], className="boundary-editor-grid"),
]), className="boundary-panel"),
], className="tab-workspace runoff-workspace"),
]),
dcc.Tab(label="4 Rainfall–Runoff", value="matching-tab", className="workflow-tab",
selected_className="workflow-tab--selected", children=[
html.Div([
panel("Match rainfall–runoff events", [
field("Maximum response time (hours)", number("response", 5, 1, 0)),
html.Button("Match events", id="match-button", className="primary"),
html.Div(id="match-status", className="status"),
field("Inspect event", dcc.Dropdown(id="event-picker",
placeholder="Run matching first")),
]),
panel("Matched-event output", [
dcc.Loading(dcc.Graph(id="pair-graph",
figure=blank("Match events to inspect a pair"))),
]),
], className="tab-workspace"),
]),
dcc.Tab(label="5 Recession", value="recession-tab", className="workflow-tab",
selected_className="workflow-tab--selected", children=[
html.Div([
panel("Recession analysis", [
html.P("Fit individual recession limbs and calculate the master recession curve.",
className="panel-note"),
html.Button("Compute master recession curve", id="recession-button",
className="primary"),
html.Div(id="recession-status", className="status"),
]),
panel("Recession output", [
dcc.Loading(dcc.Graph(id="recession-graph",
figure=blank("Run recession analysis to display results"))),
]),
], className="tab-workspace"),
]),
dcc.Tab(label="6 Hydrometrics", value="metrics-tab", className="workflow-tab",
selected_className="workflow-tab--selected", children=[
html.Div([
panel("Compute hydrometrics", [
dcc.Checklist(id="metrics", value=["tc", "rc", "ia"], options=[
{"label": "Time characteristics", "value": "tc"},
{"label": "Recession constant", "value": "rc"},
{"label": "Initial abstraction", "value": "ia"},
{"label": "Runoff / precipitation ratio", "value": "rr"},
{"label": "Antecedent precipitation", "value": "ap"},
], className="checklist"),
html.Div([
field("Drainage area (km²)", number("area", 3.6, .1, 0),
"For runoff ratio"),
field("Antecedent period (days)", number("ant-days", 3, 1, 0),
"For antecedent precipitation"),
], className="two-columns"),
html.Button("Compute hydrometrics", id="metrics-button",
className="primary"),
field("CSV filename", dcc.Input(id="filename", value="hydrun_metrics.csv")),
html.Button("Download table", id="download-button",
className="secondary"),
dcc.Download(id="download"),
html.Div(id="metrics-status", className="status"),
]),
panel("Hydrometric results", [dash_table.DataTable(
id="table", page_size=10, sort_action="native", filter_action="native",
style_table={"overflowX": "auto"},
style_cell={"fontFamily": "system-ui", "fontSize": 12, "padding": "7px",
"textAlign": "right", "minWidth": "95px"},
style_header={"fontWeight": "600", "backgroundColor": "#e2e8f0"},
)]),
], className="tab-workspace metrics-workspace"),
]),
]), className="tabs-main"),
])
@app.callback(
Output("file-status", "children"), Output("file-status", "className"),
Output("summary", "children"), Output("start-date", "date"), Output("end-date", "date"),
Output("start-date", "min_date_allowed"), Output("start-date", "max_date_allowed"),
Output("end-date", "min_date_allowed"), Output("end-date", "max_date_allowed"),
Input("streamflow-upload", "contents"),
Input("precipitation-upload", "contents"),
State("streamflow-upload", "filename"),
State("precipitation-upload", "filename"),
prevent_initial_call=True)
def upload_csv_files(streamflow_contents, precipitation_contents,
streamflow_filename, precipitation_filename):
if not streamflow_contents or not precipitation_contents:
return ("Select both streamflow and precipitation CSV files.",
"status", no_update, no_update, no_update,
no_update, no_update, no_update, no_update)
try:
flow = decode_uploaded_csv(streamflow_contents, "Streamflow")
rain = decode_uploaded_csv(precipitation_contents, "Precipitation")
reset(flow, rain)
start = mat_datetime(max(flow[0, 0], rain[0, 0])).date()
end = mat_datetime(min(flow[-1, 0], rain[-1, 0])).date()
filenames = f"Loaded: {streamflow_filename} and {precipitation_filename}"
return (filenames, "status success", summary(flow, rain),
start, end, start, end, start, end)
except Exception as error:
return (f"Load error: {error}", "status error", no_update, no_update, no_update,
no_update, no_update, no_update, no_update)
@app.callback(Output("base-graph", "figure"), Output("base-status", "children"),
Input("base-button", "n_clicks"), State("filter", "value"),
State("passes", "value"), State("start-date", "date"),
State("end-date", "date"), prevent_initial_call=True)
def run_baseflow(_, coefficient, passes, start, end):
try:
source = STATE["streamflow"]
lower = date_number(start) if start else source[0, 0]
upper = date_number(end) + 1 if end else source[-1, 0]
selected = source[(source[:, 0] >= lower) & (source[:, 0] < upper)]
storm, base = separate_baseflow(selected, float(coefficient), int(passes))
STATE.update(selected_streamflow=selected, stormflow=storm, baseflow=base)
return baseflow_plot(selected, base), f"Separated {len(selected):,} records."
except Exception as error:
return no_update, f"Error: {error}"
@app.callback(Output("runoff-graph", "figure"), Output("runoff-status", "children"),
Output("boundary-event", "options"), Output("boundary-event", "value"),
Input("runoff-button", "n_clicks"), State("threshold", "value"),
State("ratio", "value"), State("begin-slope", "value"),
State("end-slope", "value"), State("smooth", "value"),
State("duration", "value"), State("background", "value"),
prevent_initial_call=True)
def run_runoff(_, threshold, ratio, begin, end, smooth, duration, background):
try:
if "stormflow" not in STATE:
raise ValueError("Separate baseflow first.")
events, count = extract_runoff(STATE["stormflow"], float(threshold), float(ratio),
float(begin), float(end), int(smooth), int(duration or 0))
STATE["runoff_events"] = events
source = STATE["selected_streamflow"] if background == "streamflow" else STATE["stormflow"]
label = "Streamflow" if background == "streamflow" else "Baseflow-free"
options = [{"label": f"Event {i + 1}", "value": i} for i in range(count)]
return (runoff_plot(source, events, label), f"Extracted {count} runoff events.",
options, 0 if count else None)
except Exception as error:
return no_update, f"Error: {error}", no_update, no_update
@app.callback(
Output("boundary-slider", "min"), Output("boundary-slider", "max"),
Output("boundary-slider", "value"), Output("boundary-slider", "marks"),
Input("boundary-event", "value"), prevent_initial_call=True)
def select_boundary_event(event_index):
if event_index is None or not STATE.get("runoff_events"):
return 0, 1, [0, 1], {}
event = STATE["runoff_events"][int(event_index)]
stormflow = STATE["stormflow"]
start = int(np.argmin(np.abs(stormflow[:, 0] - event[0, 0])))
end = int(np.argmin(np.abs(stormflow[:, 0] - event[-1, 0])))
padding = max(8, int(round(24 / (np.median(np.diff(stormflow[:, 0])) * 24))))
lower = max(0, start - padding)
upper = min(len(stormflow) - 1, end + padding)
marks = {
lower: mat_datetime(stormflow[lower, 0]).strftime("%b %d %H:%M"),
start: "Start",
end: "End",
upper: mat_datetime(stormflow[upper, 0]).strftime("%b %d %H:%M"),
}
return lower, upper, [start, end], marks
@app.callback(
Output("boundary-start-step", "value"),
Output("boundary-end-step", "value"),
Input("boundary-slider", "value"),
Input("start-time-minus", "n_clicks"), Input("start-time-plus", "n_clicks"),
Input("end-time-minus", "n_clicks"), Input("end-time-plus", "n_clicks"),
State("boundary-start-step", "value"), State("boundary-end-step", "value"),
State("boundary-event", "value"),
prevent_initial_call=True)
def boundary_slider_to_inputs(boundaries, _start_minus, _start_plus,
_end_minus, _end_plus, start_time, end_time,
event_index):
if "stormflow" not in STATE:
return no_update, no_update
trigger = ctx.triggered_id
if trigger == "boundary-slider":
if boundaries is None or len(boundaries) != 2:
return no_update, no_update
return format_boundary_time(boundaries[0]), format_boundary_time(boundaries[1])
try:
if trigger == "start-time-minus":
return shift_boundary_time(start_time, -1, event_index), no_update
if trigger == "start-time-plus":
return shift_boundary_time(start_time, 1, event_index), no_update
if trigger == "end-time-minus":
return no_update, shift_boundary_time(end_time, -1, event_index)
if trigger == "end-time-plus":
return no_update, shift_boundary_time(end_time, 1, event_index)
except ValueError:
return no_update, no_update
return no_update, no_update
@app.callback(
Output("boundary-preview", "figure"),
Input("boundary-event", "value"),
Input("boundary-start-step", "value"),
Input("boundary-end-step", "value"))
def update_boundary_preview(event_index, start_time, end_time):
if (event_index is None or not STATE.get("runoff_events") or
not start_time or not end_time):
return blank("Select an event to preview its boundaries")
try:
start = boundary_time_to_step(start_time, event_index)
end = boundary_time_to_step(end_time, event_index)
return boundary_preview_plot(int(event_index), [start, end])
except ValueError as error:
return blank(str(error))
@app.callback(
Output("runoff-graph", "figure", allow_duplicate=True),
Output("boundary-status", "children"),
Input("boundary-button", "n_clicks"), State("boundary-event", "value"),
State("boundary-start-step", "value"), State("boundary-end-step", "value"),
State("background", "value"),
prevent_initial_call=True)
def apply_boundary_adjustment(_, event_index, start_time, end_time, background):
try:
if event_index is None or not STATE.get("runoff_events"):
raise ValueError("Select an extracted runoff event.")
start = boundary_time_to_step(start_time, event_index)
end = boundary_time_to_step(end_time, event_index)
if end <= start:
raise ValueError("The end must occur after the start.")
STATE["runoff_events"][int(event_index)] = STATE["stormflow"][start:end + 1].copy()
# Previously matched events and metrics are stale after a boundary edit.
for key in ("pairs", "relations", "recession_results"):
STATE.pop(key, None)
source = (STATE["selected_streamflow"] if background == "streamflow"
else STATE["stormflow"])
label = "Streamflow" if background == "streamflow" else "Baseflow-free"
message = (
f"Event {int(event_index) + 1} updated: "
f"{mat_datetime(STATE['stormflow'][start, 0]):%Y-%m-%d %H:%M} to "
f"{mat_datetime(STATE['stormflow'][end, 0]):%Y-%m-%d %H:%M}. "
"Run rainfall–runoff matching again."
)
return runoff_plot(source, STATE["runoff_events"], label), message
except Exception as error:
return no_update, f"Error: {error}"
@app.callback(Output("match-status", "children"), Output("event-picker", "options"),
Output("event-picker", "value"), Input("match-button", "n_clicks"),
State("response", "value"), prevent_initial_call=True)
def run_match(_, response):
try:
if not STATE.get("runoff_events"):
raise ValueError("Extract runoff events first.")
rain_events, rain_count, missing = extract_precipitation_events(STATE["precipitation"], 6)
pairs, relations = match_rainfall_runoff(rain_events, STATE["runoff_events"], float(response))
STATE.update(rain_events=rain_events, rain_missing=missing, pairs=pairs,
relations=relations, response=float(response))
options = [{"label": f"Event {i + 1} ({relations[i]['num_rain_events']} rain event(s))",
"value": i} for i in range(len(pairs))]
return f"Extracted {rain_count} rainfall events; matched {len(pairs)} pairs.", options, 0
except Exception as error:
return f"Error: {error}", [], None
@app.callback(Output("pair-graph", "figure"), Input("event-picker", "value"))
def show_pair(index):
return pair_plot(int(index)) if index is not None and "pairs" in STATE else blank("Match events first")
@app.callback(Output("recession-graph", "figure"), Output("recession-status", "children"),
Input("recession-button", "n_clicks"), prevent_initial_call=True)
def run_recession(_):
try:
if "pairs" not in STATE:
raise ValueError("Match rainfall–runoff events first.")
results = [compute_recession_constant(runoff) for _, runoff in STATE["pairs"]]
constant, r2, coefficients, curve, limbs = generalize_recession([x[2] for x in results])
STATE["recession_results"] = results
return recession_plot(curve, limbs), f"Master recession constant: {constant:.3f} h; R²: {r2:.4f}"
except Exception as error:
return no_update, f"Error: {error}"
def csv_text(rows, columns):
stream = io.StringIO()
writer = csv.DictWriter(stream, fieldnames=columns)
writer.writeheader()
writer.writerows(rows)
return stream.getvalue()
@app.callback(Output("table", "data"), Output("table", "columns"),
Output("metrics-status", "children"),
Input("metrics-button", "n_clicks"), State("metrics", "value"),
State("area", "value"), State("ant-days", "value"),
prevent_initial_call=True)
def run_metrics(_, selected, area, ant_days):
try:
if "pairs" not in STATE:
raise ValueError("Match rainfall–runoff events first.")
if not selected:
raise ValueError("Select at least one hydrometric.")
rows = []
for i, (rain, runoff) in enumerate(STATE["pairs"], 1):
row = {"Event": i}
if "tc" in selected:
row.update(dict(zip(TIME_CHARACTERISTIC_NAMES,
compute_time_characteristics(rain, runoff))))
if "rc" in selected:
rc, nrmse, _, _ = compute_recession_constant(runoff)
row.update(Recession_Constant_h=rc, Recession_NRMSE=nrmse)
if "ia" in selected:
row["Initial_Abstraction_mm"] = compute_initial_abstraction(rain, runoff)
if "rr" in selected:
if not area or area <= 0:
raise ValueError("Provide a positive drainage area.")
ratio, runoff_volume, rain_volume = compute_runoff_ratio(rain, runoff, area)
row.update(Runoff_Ratio=ratio, Runoff_Volume_m3=runoff_volume,
Precipitation_Volume_m3=rain_volume)
if "ap" in selected:
if not ant_days or ant_days <= 0:
raise ValueError("Provide a positive antecedent period.")
amount, count, fraction = compute_antecedent_precipitation(
STATE["precipitation"], runoff, ant_days, STATE.get("response", 0))
row.update(Antecedent_Precipitation_mm=amount,
Antecedent_Missing_Count=count,
Antecedent_Missing_Fraction=fraction)
rows.append(row)
names = list(rows[0])
STATE["metrics_rows"] = rows
STATE["metrics_columns"] = names
display = [{key: round(value, 6) if isinstance(value, (float, np.floating)) else value
for key, value in row.items()} for row in rows]
return (display, [{"name": name, "id": name} for name in names],
f"Computed {len(rows)} event rows. The table is ready to download.")
except Exception as error:
return no_update, no_update, f"Error: {error}"
@app.callback(
Output("download", "data"),
Input("download-button", "n_clicks"),
State("filename", "value"),
prevent_initial_call=True)
def download_metrics_table(_, filename):
if "metrics_rows" not in STATE:
return no_update
filename = filename or "hydrun_metrics.csv"
filename += "" if filename.lower().endswith(".csv") else ".csv"
return dcc.send_string(
csv_text(STATE["metrics_rows"], STATE["metrics_columns"]), filename)
if __name__ == "__main__":
app.run(debug=True)