Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1416 lines (1284 loc) · 60.7 KB
/
Copy pathapp.py
File metadata and controls
1416 lines (1284 loc) · 60.7 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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import math
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import urlopen
import folium
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from plotly.subplots import make_subplots
from streamlit.components.v1 import html
from utils.city_map import build_city_map as build_shared_city_map
from utils.env_loader import load_local_env
from utils.eda_data import (
build_citywide_trend_frame,
build_correlation_cells,
build_descriptive_stats_frame,
build_eda_quality_metrics,
build_hourly_distribution_frame,
build_weekday_hour_frame,
)
from utils.live_history import (
collect_live_snapshot,
default_live_history_db,
load_latest_live_snapshot_rows,
load_live_history_summary,
load_live_road_history,
)
from utils.live_monitor import build_live_scheduler_monitor
from utils.live_snapshot import build_live_snapshot_frame
from utils.research_models import (
run_arima_study as run_cached_arima_study,
suggest_arima_search_bounds,
)
from utils.research_exports import export_bab4_tables
from utils.research_data import (
build_city_snapshot,
load_master_traffic,
prepare_hourly_series,
score_color,
summarize_dataset,
)
from utils.live_traffic import fetch_live_overlay, provider_status
load_local_env()
st.set_page_config(page_title="Real-Time Traffic Congestion Web Mapping", layout="wide")
TARGET_OPTIONS = {
"VOL_SMP": "vol_smp",
"Jumlah Kendaraan": "vehicle_total",
}
DIRECTION_OPTIONS = ["BOTH", "INBOUND", "OUTBOUND"]
LIVE_PROVIDER_OPTIONS = ["OFF", "HERE", "TOMTOM"]
STATUS_ORDER = ["Macet", "Padat", "Lancar"]
AUTO_REFRESH_OPTIONS = {
"5 minutes": 5,
"15 minutes": 15,
"60 minutes": 60,
}
EXPORT_DIR = Path("exports") / "latest"
LIVE_HISTORY_DB = default_live_history_db("data")
LIVE_HISTORY_LOG = Path("logs") / "live_snapshot_collection.log"
LIVE_TASK_NAME_DEFAULT = "JakartaTrafficLiveSnapshotCollection"
API_BASE_URL_DEFAULT = "http://127.0.0.1:8000"
EDA_CITY_LIMIT = 168
@st.cache_data(show_spinner=False)
def get_traffic_data() -> pd.DataFrame:
return load_master_traffic("data")
@st.cache_data(show_spinner=False, ttl=60)
def get_live_history_summary_cached(provider_name: str, hours: int) -> dict[str, object]:
return load_live_history_summary(LIVE_HISTORY_DB, provider=None if provider_name in {"ALL", "AUTO"} else provider_name, hours=hours)
@st.cache_data(show_spinner=False, ttl=60)
def get_latest_live_snapshot_rows_cached(provider_name: str) -> pd.DataFrame:
return load_latest_live_snapshot_rows(
LIVE_HISTORY_DB,
provider=None if provider_name in {"ALL", "AUTO"} else provider_name,
available_only=True,
)
@st.cache_data(show_spinner=False, ttl=60)
def get_live_road_history_cached(road_name: str, provider_name: str, hours: int) -> pd.DataFrame:
return load_live_road_history(
LIVE_HISTORY_DB,
road_name=road_name,
provider=None if provider_name in {"ALL", "AUTO"} else provider_name,
hours=hours,
)
@st.cache_data(show_spinner=False, ttl=60)
def get_live_scheduler_monitor_cached(provider_name: str, hours: int) -> dict[str, object]:
return build_live_scheduler_monitor(
db_path=LIVE_HISTORY_DB,
provider=None if provider_name in {"ALL", "AUTO"} else provider_name,
hours=hours,
recent_limit=6,
log_path=LIVE_HISTORY_LOG,
tail_lines=8,
task_name=LIVE_TASK_NAME_DEFAULT,
)
@st.cache_data(show_spinner=False)
def run_arima_study(
timestamps: tuple[str, ...],
values: tuple[float, ...],
horizon: int,
pmax: int,
dmax: int,
qmax: int,
) -> dict[str, object]:
return run_cached_arima_study(timestamps, values, horizon, pmax, dmax, qmax)
def format_number(value: float, digits: int = 1) -> str:
if pd.isna(value):
return "-"
return f"{value:,.{digits}f}"
def make_live_history_chart(history_df: pd.DataFrame, road_name: str) -> go.Figure:
fig = go.Figure()
if history_df.empty:
fig.update_layout(
title=f"Collected live history: {road_name}",
template="plotly_white",
xaxis_title="Snapshot time",
yaxis_title="Speed (km/h)",
)
return fig
work = history_df.sort_values("fetched_at").copy()
fig.add_trace(
go.Scatter(
x=work["fetched_at"],
y=work["live_speed"],
mode="lines+markers",
name="Live speed",
line=dict(color="#d1495b", width=2),
)
)
fig.add_trace(
go.Scatter(
x=work["fetched_at"],
y=work["free_flow_speed"],
mode="lines",
name="Free-flow speed",
line=dict(color="#2f6690", width=2, dash="dash"),
)
)
fig.update_layout(
title=f"Collected live history: {road_name}",
template="plotly_white",
xaxis_title="Snapshot time",
yaxis_title="Speed (km/h)",
legend_title_text="Series",
margin=dict(l=20, r=20, t=60, b=20),
)
return fig
def load_export_ranking(direction_mode: str, target_col: str) -> pd.DataFrame:
export_path = EXPORT_DIR / f"road_metrics_{direction_mode.lower()}_{target_col}.csv"
if not export_path.exists():
return pd.DataFrame()
return pd.read_csv(export_path)
@st.cache_data(ttl=300, show_spinner=False)
def get_live_overlay_cached(provider_name: str, include_incidents: bool, rows: int, roads: int, date_end: str) -> dict[str, object]:
del rows, roads, date_end
return fetch_live_overlay(get_traffic_data(), provider=provider_name, include_incidents=include_incidents, force_refresh=False)
def serialize_datetime(value: object) -> str | None:
timestamp = pd.to_datetime(value, errors="coerce")
if pd.isna(timestamp):
return None
return timestamp.strftime("%Y-%m-%d %H:%M:%S")
def frame_to_records(frame: pd.DataFrame) -> list[dict[str, object]]:
work = frame.copy()
for column in work.columns:
if pd.api.types.is_datetime64_any_dtype(work[column]) or column in {"datetime", "fetched_at"}:
work[column] = work[column].map(serialize_datetime)
work = work.where(pd.notna(work), None)
return work.to_dict(orient="records")
def records_to_frame(records: list[dict[str, object]], datetime_cols: tuple[str, ...] = ()) -> pd.DataFrame:
frame = pd.DataFrame(records or [])
for column in datetime_cols:
if column in frame.columns:
frame[column] = pd.to_datetime(frame[column], errors="coerce")
return frame
def prepare_selected_series_for_eda(traffic_df: pd.DataFrame, road_name: str, direction_mode: str) -> pd.DataFrame:
series_df = prepare_hourly_series(traffic_df, road_name, direction_mode=direction_mode)
if series_df.empty:
return series_df
series_df = series_df.set_index("datetime").asfreq("h")
value_cols = [col for col in ["vehicle_total", "vol_smp", "avg_speed"] if col in series_df.columns]
if value_cols:
series_df[value_cols] = series_df[value_cols].interpolate(limit_direction="both")
return series_df.reset_index()
def build_local_eda_payload(
traffic_df: pd.DataFrame,
road_name: str,
direction_mode: str,
target_col: str,
city_limit: int,
) -> dict[str, object]:
dataset_info = summarize_dataset(traffic_df)
selected_series = prepare_selected_series_for_eda(traffic_df, road_name, direction_mode)
notes: list[str] = []
if selected_series.empty:
notes.append("Ruas atau arah terpilih tidak memiliki seri waktu yang cukup untuk panel EDA per ruas.")
return {
"dataset": {
"rows": dataset_info["rows"],
"roads": dataset_info["roads"],
"directions": dataset_info["directions"],
"date_start": str(dataset_info["date_start"]),
"date_end": str(dataset_info["date_end"]),
"coord_missing": dataset_info["coord_missing"],
},
"quality_metrics": build_eda_quality_metrics(traffic_df, selected_series),
"citywide_trend": frame_to_records(build_citywide_trend_frame(traffic_df).tail(city_limit).reset_index(drop=True)),
"correlation": frame_to_records(build_correlation_cells(traffic_df[["vehicle_total", "vol_smp", "avg_speed"]])),
"selected_series": {
"road_name": road_name,
"direction": direction_mode,
"target": target_col,
"points": int(len(selected_series)),
},
"weekday_hour": frame_to_records(build_weekday_hour_frame(selected_series, target_col)),
"hourly_distribution": frame_to_records(build_hourly_distribution_frame(selected_series, target_col)),
"descriptive_stats": frame_to_records(build_descriptive_stats_frame(selected_series)),
"notes": notes,
}
@st.cache_data(ttl=60, show_spinner=False)
def get_eda_compact_api_cached(
api_base_url: str,
road_name: str,
direction_mode: str,
target_col: str,
city_limit: int,
) -> dict[str, object]:
params = urlencode(
{
"road_name": road_name,
"direction": direction_mode,
"target": target_col,
"city_limit": int(city_limit),
}
)
url = f"{api_base_url.rstrip('/')}/v1/eda/compact?{params}"
with urlopen(url, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def make_correlation_heatmap_from_cells(cells_df: pd.DataFrame, title: str) -> go.Figure:
if cells_df.empty:
fig = go.Figure()
fig.update_layout(height=320, margin=dict(l=20, r=20, t=40, b=20), title=title)
return fig
pivot = cells_df.pivot(index="y", columns="x", values="value")
fig = go.Figure(
go.Heatmap(
z=pivot.values,
x=pivot.columns.tolist(),
y=pivot.index.tolist(),
colorscale="RdBu",
zmid=0.0,
text=np.round(pivot.values, 2),
texttemplate="%{text}",
)
)
fig.update_layout(height=320, margin=dict(l=20, r=20, t=40, b=20), title=title)
return fig
def make_weekday_hour_heatmap_from_cells(cells_df: pd.DataFrame, title: str, target_col: str) -> go.Figure:
weekday_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
if cells_df.empty:
fig = go.Figure()
fig.update_layout(height=360, margin=dict(l=20, r=20, t=40, b=20), title=title)
return fig
pivot = cells_df.pivot(index="weekday", columns="hour", values="value").reindex(weekday_order)
hour_labels = [f"{int(hour):02d}:00" for hour in pivot.columns.tolist()]
fig = go.Figure(
go.Heatmap(
z=pivot.values,
x=hour_labels,
y=pivot.index.tolist(),
colorscale="YlOrRd",
colorbar_title=target_col,
)
)
fig.update_layout(height=360, margin=dict(l=20, r=20, t=40, b=20), title=title)
return fig
def make_hourly_distribution_summary_chart(dist_df: pd.DataFrame, title: str, target_col: str) -> go.Figure:
fig = go.Figure()
if dist_df.empty:
fig.update_layout(height=360, margin=dict(l=10, r=10, t=40, b=20), title=title, xaxis_title="Hour")
return fig
work = dist_df.sort_values("hour").copy()
hours = [f"{int(hour):02d}:00" for hour in work["hour"].tolist()]
fig.add_trace(go.Scatter(x=hours, y=work["max"], mode="lines", name="Max", line=dict(color="#cbd5e0", width=1)))
fig.add_trace(
go.Scatter(
x=hours,
y=work["q3"],
mode="lines",
name="Q3",
line=dict(color="#90cdf4", width=1),
)
)
fig.add_trace(
go.Scatter(
x=hours,
y=work["q1"],
mode="lines",
name="Q1",
line=dict(color="#90cdf4", width=1),
fill="tonexty",
fillcolor="rgba(43, 108, 176, 0.18)",
)
)
fig.add_trace(
go.Scatter(
x=hours,
y=work["median"],
mode="lines+markers",
name="Median",
line=dict(color="#1a365d", width=2),
)
)
fig.add_trace(
go.Scatter(
x=hours,
y=work["mean"],
mode="lines",
name="Mean",
line=dict(color="#dd6b20", width=2, dash="dash"),
)
)
fig.add_trace(go.Scatter(x=hours, y=work["min"], mode="lines", name="Min", line=dict(color="#cbd5e0", width=1)))
fig.update_layout(
height=360,
margin=dict(l=10, r=10, t=40, b=20),
title=title,
xaxis_title="Hour",
yaxis_title=target_col,
legend_title_text="Summary",
)
return fig
def make_citywide_trend_chart(traffic_df: pd.DataFrame) -> go.Figure:
required_cols = {"datetime", "vehicle_total", "vol_smp", "avg_speed"}
if traffic_df.empty or not required_cols.issubset(set(traffic_df.columns)):
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.update_layout(height=360, margin=dict(l=10, r=10, t=30, b=20), xaxis_title="Datetime")
fig.update_yaxes(title_text="Vehicle total", secondary_y=False)
fig.update_yaxes(title_text="Avg speed (km/h)", secondary_y=True)
return fig
city_df = (
traffic_df.groupby("datetime", as_index=False)
.agg(vehicle_total=("vehicle_total", "sum"), vol_smp=("vol_smp", "sum"), avg_speed=("avg_speed", "mean"))
.sort_values("datetime")
)
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(
x=city_df["datetime"],
y=city_df["vehicle_total"],
name="Vehicle total",
mode="lines",
line=dict(color="#1a365d", width=2),
),
secondary_y=False,
)
fig.add_trace(
go.Scatter(
x=city_df["datetime"],
y=city_df["avg_speed"],
name="Avg speed",
mode="lines",
line=dict(color="#dd6b20", width=2),
),
secondary_y=True,
)
fig.update_layout(height=360, margin=dict(l=10, r=10, t=30, b=20), xaxis_title="Datetime")
fig.update_yaxes(title_text="Vehicle total", secondary_y=False)
fig.update_yaxes(title_text="Avg speed (km/h)", secondary_y=True)
return fig
def make_correlation_heatmap(frame: pd.DataFrame, title: str) -> go.Figure:
numeric_cols = [col for col in ["vehicle_total", "vol_smp", "avg_speed"] if col in frame.columns]
corr = frame[numeric_cols].corr(numeric_only=True).fillna(0.0)
fig = go.Figure(
go.Heatmap(
z=corr.values,
x=corr.columns.tolist(),
y=corr.index.tolist(),
colorscale="RdBu",
zmid=0.0,
text=np.round(corr.values, 2),
texttemplate="%{text}",
)
)
fig.update_layout(height=320, margin=dict(l=20, r=20, t=40, b=20), title=title)
return fig
def make_weekday_hour_heatmap(series_df: pd.DataFrame, target_col: str, title: str) -> go.Figure:
weekday_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
work = series_df.copy()
work["weekday"] = work["datetime"].dt.day_name()
work["hour"] = work["datetime"].dt.hour
pivot = work.pivot_table(index="weekday", columns="hour", values=target_col, aggfunc="mean").reindex(weekday_order)
fig = go.Figure(
go.Heatmap(
z=pivot.values,
x=[f"{int(hour):02d}:00" for hour in pivot.columns.tolist()],
y=pivot.index.tolist(),
colorscale="YlOrRd",
colorbar_title=target_col,
)
)
fig.update_layout(height=360, margin=dict(l=20, r=20, t=40, b=20), title=title)
return fig
def make_hourly_box_chart(series_df: pd.DataFrame, target_col: str, title: str) -> go.Figure:
work = series_df.copy()
work["hour"] = work["datetime"].dt.hour
fig = go.Figure()
for hour in sorted(work["hour"].dropna().unique().tolist()):
hour_df = work[work["hour"] == hour]
fig.add_trace(
go.Box(
y=hour_df[target_col],
name=f"{int(hour):02d}",
boxpoints=False,
marker_color="#2b6cb0",
line=dict(width=1),
)
)
fig.update_layout(height=360, margin=dict(l=10, r=10, t=40, b=20), title=title, xaxis_title="Hour")
return fig
def inject_auto_refresh(interval_ms: int) -> None:
html(
f"""
<script>
const interval = {interval_ms};
const now = Date.now();
const next = Math.ceil(now / interval) * interval;
const delay = Math.max(1000, next - now + 1000);
window.setTimeout(function() {{
window.parent.location.reload();
}}, delay);
</script>
""",
height=0,
)
def build_city_map(
snapshot: pd.DataFrame,
live_overlay: dict[str, object] | None = None,
focus_road: str | None = None,
) -> folium.Map:
return build_shared_city_map(snapshot, live_overlay=live_overlay, focus_road=focus_road, data_dir=Path("data"))
def make_status_bar(snapshot: pd.DataFrame) -> go.Figure:
counts = (
snapshot["status"].value_counts().reindex(STATUS_ORDER, fill_value=0).reset_index()
)
counts.columns = ["status", "count"]
fig = go.Figure(
go.Bar(
x=counts["status"],
y=counts["count"],
marker_color=[score_color(status) for status in counts["status"]],
)
)
fig.update_layout(height=320, margin=dict(l=10, r=10, t=20, b=20), xaxis_title="Status", yaxis_title="Jumlah ruas")
return fig
def make_profile_chart(series_df: pd.DataFrame, target_col: str) -> go.Figure:
hourly = series_df.copy()
hourly["hour"] = hourly["datetime"].dt.hour
profile = hourly.groupby("hour", as_index=False).agg(target=(target_col, "mean"), speed=("avg_speed", "mean"))
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Bar(x=profile["hour"], y=profile["target"], name="Rata-rata target", marker_color="#2b6cb0"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=profile["hour"], y=profile["speed"], name="Rata-rata speed", mode="lines+markers", line=dict(color="#dd6b20")),
secondary_y=True,
)
fig.update_layout(height=360, margin=dict(l=10, r=10, t=30, b=20), xaxis_title="Jam")
fig.update_yaxes(title_text="Target", secondary_y=False)
fig.update_yaxes(title_text="Avg speed (km/h)", secondary_y=True)
return fig
def make_history_chart(series_df: pd.DataFrame, target_col: str, target_label: str) -> go.Figure:
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(
x=series_df["datetime"],
y=series_df[target_col],
name=target_label,
mode="lines",
line=dict(color="#1a365d"),
),
secondary_y=False,
)
fig.add_trace(
go.Scatter(
x=series_df["datetime"],
y=series_df["avg_speed"],
name="Avg speed",
mode="lines",
line=dict(color="#dd6b20"),
),
secondary_y=True,
)
fig.update_layout(height=400, margin=dict(l=10, r=10, t=30, b=20), xaxis_title="Waktu")
fig.update_yaxes(title_text=target_label, secondary_y=False)
fig.update_yaxes(title_text="Avg speed (km/h)", secondary_y=True)
return fig
def make_forecast_chart(study: dict[str, object], target_label: str) -> go.Figure:
actual_df = study["series"]
forecast_df = study["forecast"]
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=actual_df["datetime"],
y=actual_df["actual"],
name=f"Actual {target_label}",
mode="lines",
line=dict(color="#1a365d"),
)
)
fig.add_trace(
go.Scatter(
x=forecast_df["datetime"],
y=forecast_df["forecast"],
name="Forecast",
mode="lines",
line=dict(color="#c53030"),
)
)
fig.add_trace(
go.Scatter(
x=np.concatenate([forecast_df["datetime"], forecast_df["datetime"][::-1]]),
y=np.concatenate([forecast_df["ci_lower"], forecast_df["ci_upper"][::-1]]),
fill="toself",
line=dict(width=0),
opacity=0.2,
name="95% CI",
)
)
fig.update_layout(height=400, margin=dict(l=10, r=10, t=30, b=20), xaxis_title="Waktu")
return fig
def make_holdout_chart(study: dict[str, object], target_label: str) -> go.Figure:
holdout_df = study["test_predictions"]
fig = go.Figure()
fig.add_trace(go.Scatter(x=holdout_df["datetime"], y=holdout_df["actual"], name="Actual", mode="lines", line=dict(color="#1a365d")))
fig.add_trace(go.Scatter(x=holdout_df["datetime"], y=holdout_df["predicted"], name="Predicted", mode="lines", line=dict(color="#2f855a")))
fig.update_layout(height=340, margin=dict(l=10, r=10, t=25, b=20), xaxis_title="Waktu", yaxis_title=target_label)
return fig
def make_lag_chart(df: pd.DataFrame, title: str) -> go.Figure:
fig = go.Figure(go.Bar(x=df["lag"], y=df["value"], marker_color="#2b6cb0"))
fig.add_hline(y=0.0, line_width=1, line_color="#4a5568")
fig.update_layout(height=320, margin=dict(l=10, r=10, t=35, b=20), title=title, xaxis_title="Lag")
return fig
def make_residual_chart(df: pd.DataFrame) -> go.Figure:
fig = go.Figure(go.Scatter(x=df["step"], y=df["residual"], mode="lines", line=dict(color="#805ad5"), name="Residual"))
fig.add_hline(y=0.0, line_width=1, line_color="#4a5568")
fig.update_layout(height=320, margin=dict(l=10, r=10, t=25, b=20), xaxis_title="Urutan residual", yaxis_title="Residual")
return fig
traffic = get_traffic_data()
summary = summarize_dataset(traffic)
latest_time = traffic["datetime"].max()
road_options = sorted(traffic["road_name"].unique().tolist())
st.sidebar.title("Research Controls")
st.sidebar.caption("Dashboard ini menggabungkan dataset lalu lintas per jam untuk pemodelan ARIMA dan snapshot live periodik untuk real-time web mapping.")
st.sidebar.write(f"Latest available data: {latest_time:%Y-%m-%d %H:%M}")
if st.sidebar.button("Reload cached data"):
st.cache_data.clear()
st.rerun()
auto_refresh_enabled = st.sidebar.toggle("Auto refresh dashboard", value=True)
auto_refresh_label = st.sidebar.selectbox("Auto refresh interval", list(AUTO_REFRESH_OPTIONS.keys()), index=0, disabled=not auto_refresh_enabled)
auto_refresh_minutes = AUTO_REFRESH_OPTIONS[auto_refresh_label]
if auto_refresh_enabled:
inject_auto_refresh(auto_refresh_minutes * 60 * 1000)
st.sidebar.caption(f"Halaman akan refresh otomatis setiap {auto_refresh_minutes} menit.")
live_status = provider_status()
default_live_provider = live_status["default_provider"] if live_status["default_provider"] in LIVE_PROVIDER_OPTIONS else "OFF"
st.sidebar.subheader("Live Overlay")
st.sidebar.caption(
"Mode hybrid: dataset skripsi tetap menjadi sumber analisis utama, sedangkan overlay live dipakai untuk pembacaan kondisi eksternal terbaru."
)
live_provider = st.sidebar.selectbox(
"External live provider",
LIVE_PROVIDER_OPTIONS,
index=LIVE_PROVIDER_OPTIONS.index(default_live_provider),
)
live_include_incidents = st.sidebar.checkbox("Include incidents", value=True)
live_history_hours = st.sidebar.selectbox("Live history window", [6, 12, 24, 48, 72], index=2)
st.sidebar.caption(
f"HERE key: {'available' if live_status['providers']['HERE'] else 'missing'} | "
f"TomTom key: {'available' if live_status['providers']['TOMTOM'] else 'missing'}"
)
live_force_refresh = st.sidebar.button("Refresh live overlay")
store_live_snapshot_now = st.sidebar.button("Store live snapshot now")
store_live_result = None
if store_live_snapshot_now:
store_provider = live_provider if live_provider != "OFF" else default_live_provider
if store_provider == "OFF":
st.sidebar.warning("Pilih provider live yang aktif sebelum menyimpan snapshot.")
else:
collection = collect_live_snapshot(
data_dir="data",
db_path=LIVE_HISTORY_DB,
provider=store_provider,
include_incidents=live_include_incidents,
force_refresh=True,
)
store_live_result = collection["stored"]
get_live_history_summary_cached.clear()
get_latest_live_snapshot_rows_cached.clear()
get_live_road_history_cached.clear()
get_live_scheduler_monitor_cached.clear()
st.sidebar.success(
f"Snapshot live tersimpan: #{store_live_result['snapshot_id']} "
f"({store_live_result['road_match_count']} ruas)"
)
history_provider = live_provider if live_provider != "OFF" else "AUTO"
live_collection_summary = get_live_history_summary_cached(history_provider, live_history_hours)
latest_collected_live = get_latest_live_snapshot_rows_cached(history_provider)
live_scheduler_monitor = get_live_scheduler_monitor_cached(history_provider, live_history_hours)
live_snapshot, live_snapshot_time, live_snapshot_provider = build_live_snapshot_frame(latest_collected_live, traffic)
live_snapshot_provider = live_snapshot_provider or "-"
snapshot_source_options = ["Latest collected live", "Research dataset"] if not live_snapshot.empty else ["Research dataset"]
snapshot_source = st.sidebar.radio("City snapshot source", snapshot_source_options, index=0, horizontal=False)
use_live_snapshot = snapshot_source == "Latest collected live" and not live_snapshot.empty
if use_live_snapshot and live_snapshot_time is not None and not pd.isna(live_snapshot_time):
st.sidebar.caption(
f"Snapshot kota default memakai live collection terakhir: {live_snapshot_time:%Y-%m-%d %H:%M} "
f"({live_snapshot_provider})."
)
st.sidebar.caption("Kontrol tanggal dan jam historis dinonaktifkan sampai sumber snapshot diganti ke Research dataset.")
elif use_live_snapshot:
st.sidebar.caption("Snapshot kota default memakai latest collected live snapshot.")
else:
st.sidebar.caption("Snapshot kota memakai dataset penelitian; pilih tanggal dan jam historis di bawah.")
available_dates = sorted(pd.Series(traffic["date"].unique()).tolist())
default_date = latest_time.date()
selected_date = st.sidebar.date_input(
"Snapshot date",
value=default_date,
min_value=min(available_dates),
max_value=max(available_dates),
disabled=use_live_snapshot,
)
selected_day = traffic[traffic["date"] == selected_date]
if selected_day.empty:
selected_day = traffic[traffic["date"] == default_date]
selected_date = default_date
available_hours = sorted(selected_day["datetime"].dt.strftime("%H:%M").unique().tolist())
default_hour = latest_time.strftime("%H:%M") if selected_date == default_date else available_hours[-1]
if default_hour not in available_hours:
default_hour = available_hours[-1]
selected_hour = st.sidebar.selectbox(
"Snapshot hour",
available_hours,
index=available_hours.index(default_hour),
disabled=use_live_snapshot,
)
overview_direction = st.sidebar.radio("Dashboard direction", DIRECTION_OPTIONS, index=0, horizontal=False)
if use_live_snapshot:
st.sidebar.caption("Arah dashboard tetap dipakai untuk analisis historis, forecast, dan export. Snapshot live sendiri tidak dipisah per arah.")
selected_road = st.sidebar.selectbox("Detail road", road_options, index=road_options.index("Antasari") if "Antasari" in road_options else 0)
detail_direction = st.sidebar.radio("Detail direction", DIRECTION_OPTIONS, index=0, horizontal=False)
target_label = st.sidebar.selectbox("Forecast target", list(TARGET_OPTIONS.keys()), index=0)
target_col = TARGET_OPTIONS[target_label]
horizon = st.sidebar.slider("Forecast horizon (hours)", 1, 24, 6)
snapshot_time = pd.Timestamp(f"{selected_date} {selected_hour}")
research_snapshot = build_city_snapshot(traffic, snapshot_time, direction_mode=overview_direction)
current_snapshot = live_snapshot if use_live_snapshot else research_snapshot
current_snapshot_time = live_snapshot_time if use_live_snapshot and live_snapshot_time is not None and not pd.isna(live_snapshot_time) else snapshot_time
has_live_snapshot_fallback = use_live_snapshot and not live_snapshot.empty and live_snapshot_time is not None and not pd.isna(live_snapshot_time)
selected_series = prepare_selected_series_for_eda(traffic, selected_road, direction_mode=detail_direction)
order_search_mode = st.sidebar.radio("ARIMA order search", ["Automatic", "Manual"], index=0, horizontal=False)
default_search_bounds = {
"pmax": 2,
"dmax": 1,
"qmax": 2,
"rationale": "Seri waktu belum cukup untuk inferensi batas pencarian otomatis, sehingga default konservatif dipakai.",
}
auto_search_bounds = default_search_bounds
if not selected_series.empty and target_col in selected_series.columns:
auto_search_bounds = suggest_arima_search_bounds(selected_series[target_col])
if order_search_mode == "Automatic":
pmax = int(auto_search_bounds["pmax"])
dmax = int(auto_search_bounds["dmax"])
qmax = int(auto_search_bounds["qmax"])
st.sidebar.caption(
f"Pencarian orde otomatis: p=0..{pmax}, d=0..{dmax}, q=0..{qmax}."
)
st.sidebar.caption(str(auto_search_bounds.get("rationale") or ""))
else:
pmax = st.sidebar.slider("Max p and q", 1, 4, 2)
dmax = st.sidebar.slider("Max d", 0, 2, 1)
qmax = pmax
st.sidebar.caption(
f"Pencarian orde manual: p=0..{pmax}, d=0..{dmax}, q=0..{qmax}."
)
eda_payload_source = f"API endpoint ({API_BASE_URL_DEFAULT}/v1/eda/compact)"
eda_payload_warning = ""
try:
eda_payload = get_eda_compact_api_cached(
API_BASE_URL_DEFAULT,
selected_road,
detail_direction,
target_col,
EDA_CITY_LIMIT,
)
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
eda_payload = build_local_eda_payload(traffic, selected_road, detail_direction, target_col, EDA_CITY_LIMIT)
eda_payload_source = "Local fallback (API tidak aktif atau gagal diakses)"
eda_payload_warning = str(exc)
eda_dataset = eda_payload.get("dataset", {})
eda_quality_df = records_to_frame(eda_payload.get("quality_metrics", []))
eda_citywide_trend_df = records_to_frame(eda_payload.get("citywide_trend", []), datetime_cols=("datetime",))
eda_correlation_df = records_to_frame(eda_payload.get("correlation", []))
eda_weekday_hour_df = records_to_frame(eda_payload.get("weekday_hour", []))
eda_hourly_distribution_df = records_to_frame(eda_payload.get("hourly_distribution", []))
eda_descriptive_df = records_to_frame(eda_payload.get("descriptive_stats", []))
eda_selected_meta = eda_payload.get("selected_series", {})
eda_notes = eda_payload.get("notes", [])
live_overlay = None
if live_provider != "OFF":
if live_force_refresh:
live_overlay = fetch_live_overlay(traffic, provider=live_provider, include_incidents=live_include_incidents, force_refresh=True)
else:
live_overlay = get_live_overlay_cached(
live_provider,
live_include_incidents,
summary["rows"],
summary["roads"],
str(summary["date_end"]),
)
selected_live_history = get_live_road_history_cached(selected_road, history_provider, live_history_hours)
study = None
if not selected_series.empty:
study = run_arima_study(
tuple(selected_series["datetime"].dt.strftime("%Y-%m-%d %H:%M:%S")),
tuple(selected_series[target_col].astype(float).tolist()),
horizon,
pmax,
dmax,
qmax,
)
st.title("Real-Time Traffic Congestion Web Mapping Using Statistical Time-Series Regression Model")
st.caption("Interactive Jakarta traffic web mapping with periodic live updates and ARIMA-based statistical time-series prediction.")
st.info(
"Implementasi ini mengikuti tujuan penelitian: menyajikan pemetaan kemacetan kota secara real-time berbasis update periodik, "
"serta prediksi statistik deret waktu ARIMA untuk analisis per ruas dan evaluasi 80:20."
)
snapshot_source_caption = "Latest collected live snapshot" if use_live_snapshot else f"Research dataset snapshot ({overview_direction})"
if use_live_snapshot and live_snapshot_provider != "-":
snapshot_source_caption += f" | Provider: {live_snapshot_provider}"
st.caption(f"City snapshot aktif: {snapshot_source_caption}")
kpi_left, kpi_mid, kpi_right, kpi_last = st.columns(4)
kpi_left.metric("Roads in dataset", summary["roads"])
kpi_mid.metric("Rows", f"{summary['rows']:,}")
kpi_right.metric("Directions", summary["directions"])
kpi_last.metric("Snapshot", current_snapshot_time.strftime("%d %b %Y %H:%M") if not pd.isna(current_snapshot_time) else "-")
overview_tab, detail_tab, eda_tab, validation_tab, export_tab, methodology_tab = st.tabs(
["Real-Time City Mapping", "Road Detail", "EDA", "Validation", "Research Exports", "Methodology"]
)
with overview_tab:
if current_snapshot.empty:
if use_live_snapshot:
st.warning("Belum ada latest collected live snapshot yang bisa ditampilkan.")
else:
st.warning("Tidak ada data pada snapshot yang dipilih.")
else:
top_road = current_snapshot.iloc[0]
overview_a, overview_b, overview_c, overview_d = st.columns(4)
if use_live_snapshot:
overview_a.metric("Mapped live roads", int(current_snapshot["latitude"].notna().sum()))
overview_b.metric("Live road matches", int(len(current_snapshot)))
overview_c.metric("Mean live speed", f"{current_snapshot['avg_speed'].mean():.1f} km/h")
overview_d.metric("Top live congestion", f"{top_road.road_name} ({top_road.congestion_score:.1f})")
st.caption("Default city dashboard sekarang memakai latest collected live snapshot. Grafik historis dan ARIMA tetap memakai dataset penelitian.")
else:
overview_a.metric("Mapped roads", int(current_snapshot["latitude"].notna().sum()))
overview_b.metric("Total vehicles", f"{current_snapshot['vehicle_total'].sum():,.0f}")
overview_c.metric("Mean speed", f"{current_snapshot['avg_speed'].mean():.1f} km/h")
overview_d.metric("Top congestion", f"{top_road.road_name} ({top_road.congestion_score:.1f})")
if live_provider != "OFF":
st.subheader("External live overlay")
if not live_overlay:
st.info("Live overlay belum dimuat.")
elif not live_overlay.get("available"):
live_error = live_overlay.get("error") or "Live overlay tidak tersedia."
if has_live_snapshot_fallback:
st.info(
f"Permintaan live baru ke {live_provider} belum berhasil. "
f"Dashboard tetap memakai latest successful live snapshot "
f"{current_snapshot_time:%Y-%m-%d %H:%M} ({live_snapshot_provider}). "
f"Detail terakhir dari provider: {live_error}"
)
else:
st.warning(live_error)
else:
live_meta = live_overlay.get("meta", {})
live_a, live_b, live_c, live_d = st.columns(4)
live_a.metric("Provider", live_overlay.get("provider", "-"))
live_b.metric("Live flow items", int(live_meta.get("flow_count", len(live_overlay.get("flow_items", [])))))
live_c.metric("Live incidents", int(live_meta.get("incident_count", len(live_overlay.get("incident_items", [])))))
live_d.metric("Fetched at", live_overlay.get("fetched_at") or "-")
if live_overlay.get("warnings"):
warning_rows = live_overlay["warnings"]
if len(warning_rows) == 1:
st.info(str(warning_rows[0]))
else:
st.info(f"{len(warning_rows)} warning live overlay. Contoh: {warning_rows[0]}")
st.subheader("Collected live history")
if live_collection_summary["total_snapshots"] == 0:
st.info(
"Histori live belum terkumpul. Gunakan tombol `Store live snapshot now` "
"atau jalankan scheduler koleksi otomatis."
)
else:
hist_a, hist_b, hist_c, hist_d = st.columns(4)
hist_a.metric("Snapshots stored", int(live_collection_summary["total_snapshots"]))
hist_b.metric(
f"Last {live_collection_summary['window_hours']}h",
int(live_collection_summary["snapshots_last_window"]),
)
hist_c.metric("Latest collected", live_collection_summary.get("latest_fetched_at") or "-")
hist_d.metric("Road matches", int(live_collection_summary["latest_road_match_count"]))
if live_collection_summary.get("latest_error"):
if has_live_snapshot_fallback:
st.info(
f"Koleksi live terbaru gagal, tetapi snapshot aktif tetap memakai hasil sukses terakhir "
f"{current_snapshot_time:%Y-%m-%d %H:%M} ({live_snapshot_provider}). "
f"Error collector terakhir: {live_collection_summary['latest_error']}"
)
else:
st.warning(f"Snapshot terakhir error: {live_collection_summary['latest_error']}")
if not latest_collected_live.empty:
st.dataframe(
latest_collected_live.head(20),
use_container_width=True,
hide_index=True,
)
st.subheader("Live scheduler monitor")
scheduler_task = live_scheduler_monitor.get("task", {})
sched_a, sched_b, sched_c, sched_d = st.columns(4)
sched_a.metric("Task state", scheduler_task.get("state") or ("Missing" if not scheduler_task.get("exists") else "-"))
sched_b.metric("Next run", scheduler_task.get("next_run_time") or "-")
sched_c.metric("Last run", scheduler_task.get("last_run_time") or "-")
sched_d.metric("Last result", scheduler_task.get("last_task_result") if scheduler_task.get("last_task_result") is not None else "-")
if scheduler_task.get("error"):
st.warning(f"Scheduler monitor error: {scheduler_task['error']}")
elif not scheduler_task.get("exists"):
st.info("Scheduled task koleksi live belum terdaftar. Gunakan scripts/register_live_snapshot_task.ps1 atau setup_live_snapshot_automation.ps1.")
else:
st.caption(
f"Task `{scheduler_task.get('task_name')}` state `{scheduler_task.get('state')}` "
f"dengan interval `{scheduler_task.get('repetition_interval') or '-'}`."
)
recent_monitor_rows = pd.DataFrame(live_scheduler_monitor.get("recent_snapshots", []))
monitor_left, monitor_right = st.columns(2)
with monitor_left:
if recent_monitor_rows.empty:
st.info("Belum ada snapshot recent untuk panel monitor.")
else:
st.dataframe(recent_monitor_rows.head(6), use_container_width=True, hide_index=True)
with monitor_right:
log_tail = live_scheduler_monitor.get("log_tail", [])
if log_tail:
st.code("\n".join(str(line) for line in log_tail), language="text")
else:
st.info(f"Log scheduler belum tersedia di {live_scheduler_monitor.get('log_path')}.")
map_col, status_col = st.columns([2, 1])
with map_col:
st.subheader("Interactive congestion map")
map_view_mode = st.radio(
"Map view",
["Focused selected road area", "Citywide overview"],
horizontal=True,
key="city_map_view_mode",
)
map_overlay = live_overlay if use_live_snapshot else None
focus_map = map_view_mode == "Focused selected road area"
city_map = build_city_map(
current_snapshot,
live_overlay=map_overlay,
focus_road=selected_road if focus_map else None,
)
if focus_map:
st.caption(
"Peta difokuskan ke ruas yang dipilih. Koridor hijau, oranye, dan merah mengikuti centerline/polyline "
"ruas yang tersimpan pada cache geometry lokal agar bentuk jalan tetap terbaca."
)
elif use_live_snapshot and map_overlay and map_overlay.get("available"):
st.caption("Mode live citywide menampilkan koridor semua ruas dari centerline/polyline cache sesuai status snapshot aktif.")
html(city_map._repr_html_(), height=560)
with status_col:
st.subheader("Status distribution")
st.plotly_chart(make_status_bar(current_snapshot), use_container_width=True)
snapshot_table_cols = (
["road_name", "status", "congestion_score", "avg_speed", "free_flow_speed", "provider_name"]
if use_live_snapshot
else ["road_name", "status", "congestion_score", "vehicle_total", "vol_smp", "avg_speed"]
)
st.dataframe(
current_snapshot[[col for col in snapshot_table_cols if col in current_snapshot.columns]].head(10),
use_container_width=True,
hide_index=True,
)