forked from pozapas/PEDAT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdash_beta.py
1546 lines (1324 loc) · 70 KB
/
dash_beta.py
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
# Pedestrian Volume Data Visualization Dashboard (PEDAT)
# Author: Amir Rafe ([email protected])
# File: dash_beta.py
# Version: 1.0.17.beta
# About: A streamlit webapp to visualize pedestrian volum data in Utah
# Streamlit for web app functionality
import streamlit as st
import streamlit.components.v1 as components
from streamlit_folium import st_folium
# Data manipulation and analysis
import pandas as pd
import numpy as np
import json
# Visualization libraries
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import plotly.io as pio
import matplotlib.pyplot as plt
import matplotlib.colors
import folium
from folium.plugins import Draw, MarkerCluster, Search, FastMarkerCluster
import pydeck as pdk
import branca.colormap as cm
from branca.colormap import linear
# Date and time handling
from datetime import datetime, date, timedelta
import pytz
import time
# Geospatial and geometry operations
from shapely.geometry import Polygon, Point
# PDF and image handling
from fpdf import FPDF
from PIL import Image
from reportlab.lib.pagesizes import landscape, letter, A4
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
import imgkit
import tempfile
from io import BytesIO
from tempfile import NamedTemporaryFile
# Google Cloud services
from google.cloud import bigquery
from google.oauth2 import service_account
# Miscellaneous utilities
import os
import base64
import threading
import random
import copy
import kaleido
# Setting default scale for kaleido
pio.kaleido.scope.default_scale = 2
# Create API client.
# credentials = service_account.Credentials.from_service_account_info(
# st.secrets["gcp_service_account"]
# )
client = bigquery.Client() # credentials=credentials
# Define SQL query to retrieve the data from BigQuery
sql_query = """
SELECT *
FROM `ut-udot-pedat-dev.pedat_dataset.map_data`
"""
sql_query2 = """
SELECT *
FROM `ut-udot-pedat-dev.pedat_dataset.pedatutah`
WHERE ADDRESS IN UNNEST(@selected_signals)
"""
sql_query3 = """
SELECT *
FROM `ut-udot-pedat-dev.pedat_dataset.pedatdaily`
WHERE ADDRESS IN UNNEST(@selected_signals)
"""
# Define the title
title = 'Pedestrian Volume Data Visualization Dashboard'
text1 = 'This website provides data and visualizations of pedestrian volume at various locations in Utah. "Pedestrian volume" is an estimate of pedestrian crossing volume at an intersection, currently based on pedestrian push-button presses at traffic signals. See the "How to use" and "Notes" tabs on the left, or following the step-by-step instructions below.'
text2 = 'As of 10/31/2023, this website contains pedestrian volume data for 2,030 locations in Utah between 2018 and 2022.'
# Define the x and y axis labels
x_axis_label = 'TIME1'
y_axis_label = 'PED'
# Generating a randomized color map for unique signals
def create_color_map(unique_signals):
colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_signals)))
colors = [matplotlib.colors.rgb2hex(c) for c in colors]
random.shuffle(colors) # Shuffle colors for variety
color_map = dict(zip(unique_signals, colors))
return color_map
@st.cache_resource
# Formatting numerical values into readable metrics (B, M, K)
def format_metric(value):
# Check if the value is greater than or equal to 1 billion
if value >= 1e9:
return f'{round(value/1e9,1)} B'
# Check if the value is greater than or equal to 1 million
elif value >= 1e6:
return f'{round(value/1e6,1)} M'
# Check if the value is greater than or equal to 1 thousand
elif value >= 1e3:
return f'{round(value/1e3,1)} K'
# Otherwise, return the value as is
else:
return str(value)
@st.cache_resource
# creating a time-series chart with custom aggregation and filtering options
def make_chart(df, signals, start_date, end_date, aggregation_method, location, Dash_selected, color_map, template='plotly'):
if aggregation_method == 'Hour':
groupby = ['SIGNAL','ADDRESS', pd.Grouper(key='TIME1', freq='1H')]
elif aggregation_method == 'Day':
groupby = ['SIGNAL','ADDRESS', pd.Grouper(key='TIME1', freq='1D')]
elif aggregation_method == 'Week':
groupby = ['SIGNAL','ADDRESS', pd.Grouper(key='TIME1', freq='1W')]
elif aggregation_method == 'Month':
groupby = ['SIGNAL','ADDRESS', pd.Grouper(key='TIME1', freq='1M')]
elif aggregation_method == 'Year':
groupby = ['SIGNAL','ADDRESS', pd.Grouper(key='TIME1', freq='1Y')]
if location == 'All':
filter_val = 'all'
col = 'PED'
else:
filter_val = location.split()[-1]
col = 'P'
# Filter the dataframe by the selected signals and date range
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df[(df['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) & (df['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC')) & (df['ADDRESS'].isin(signals))]
else:
df_filtered = df[(df['TIME1'] >= start_date) & (df['TIME1'] <= end_date) & (df['ADDRESS'].isin(signals))]
# Aggregate the data
if location == 'All':
df_agg = df_filtered.groupby(groupby).agg({'PED': 'sum'}).reset_index()
df_agg['PED'] = df_agg['PED'].round(0)
df_agg = df_agg.rename(columns={'SIGNAL': 'Signal ID', 'TIME1':'Timestamp' , 'PED':'Pedestrian'})
else:
df_agg = df_filtered[df_filtered['P'] == int(filter_val)].groupby(groupby).agg({'PED': 'sum'}).reset_index()
df_agg['PED'] = df_agg['PED'].round(0)
df_agg = df_agg.rename(columns={'SIGNAL': 'Signal ID' , 'TIME1':'Timestamp' , 'PED':'Pedestrian'})
# Modify address for display, but this won't directly affect coloring or legend
df_agg['Address'] = df_agg['ADDRESS'].str.replace(r'^\d+\s*--\s*', '', regex=True)
# Create the line chart
if aggregation_method == 'Hour':
x_axis_label = '<b>Time<b>'
fig = px.line(df_agg, x='Timestamp', y='Pedestrian', color='Signal ID',
hover_data=['Pedestrian', 'Timestamp', 'Address'],
color_discrete_map=color_map, template=template)
else:
x_axis_label = '<b>Date<b>'
fig = px.line(df_agg, x='Timestamp', y='Pedestrian', color='Signal ID',
hover_data=['Pedestrian', 'Timestamp', 'Address'],
color_discrete_map=color_map, template=template)
fig.update_xaxes(title_text=x_axis_label)
fig.update_yaxes(title_text='<b>Pedestrian Volume<b>')
fig.update_traces(line=dict(width=3))
fig.update_layout(showlegend=True , legend_title_text='<b>Location<b>')
# Set the time slider at the bottom
fig.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1, label="1d", step="day", stepmode="backward"),
dict(count=7, label="1w", step="day", stepmode="backward"),
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(step="all")
])
),
rangeslider=dict(
visible=True
),
type="date"
)
)
fig6 = copy.deepcopy(fig)
fig6.update_layout(xaxis=dict(rangeselector=dict(visible=False ),rangeslider=dict(visible=False),type="date"))
fig6.update_layout(
showlegend=True,
legend_title_text='<b>Location<b>',
template='plotly',
autosize=False,
width=920,
height=520
)
fig6.write_image("fig1.png")
return fig
@st.cache_resource
# Aggregating and formatting data for table display based on selected criteria
def make_table(df, signals, start_date, end_date, aggregation_method, location,Dash_selected):
if aggregation_method == 'Hour':
groupby = ['ADDRESS', pd.Grouper(key='TIME1', freq='1H')]
elif aggregation_method == 'Day':
groupby = ['ADDRESS', pd.Grouper(key='TIME1', freq='1D')]
elif aggregation_method == 'Week':
groupby = ['ADDRESS', pd.Grouper(key='TIME1', freq='1W')]
elif aggregation_method == 'Month':
groupby = ['ADDRESS', pd.Grouper(key='TIME1', freq='1M')]
elif aggregation_method == 'Year':
groupby = ['ADDRESS', pd.Grouper(key='TIME1', freq='1Y')]
if location == 'All':
filter_val = 'all'
col = 'PED'
else:
filter_val = location.split()[-1]
col = 'P'
# Filter the dataframe by the selected signals and date range
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df[(df['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) & (df['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC')) & (df['ADDRESS'].isin(signals))]
else:
df_filtered = df[(df['TIME1'] >= start_date) & (df['TIME1'] <= end_date) & (df['ADDRESS'].isin(signals))]
# Aggregate the data
if location == 'All':
df_agg = df_filtered.groupby(groupby).agg({'PED': 'sum', 'CITY': 'first', 'SIGNAL': 'first' , 'LAT': 'first' , 'LNG': 'first' }).reset_index()
else:
df_agg = df_filtered[df_filtered['P'] == int(filter_val)].groupby(groupby).agg({'PED': 'sum', 'P': 'first', 'CITY': 'first', 'SIGNAL': 'first' , 'LAT': 'first' , 'LNG': 'first'}).reset_index()
df_agg['PED'] = df_agg['PED'].round(0)
df_agg.rename(columns={'SIGNAL': 'Signal ID' , 'ADDRESS': 'Address' , 'TIME1':'Timestamp' , 'PED':'Pedestrian' , 'CITY':'City' , 'P': 'Phase' , 'LAT':'Latitude' , 'LNG': 'Longtitude' }, inplace=True)
# Split the 'Address' column on '--' and take the second part if it exists
df_agg['Address'] = df_agg['Address'].apply(lambda x: x.split('-- ')[1] if '--' in x else x)
# Continue with the existing code to select columns and reset index...
if 'Phase' in df_agg.columns:
df_agg = df_agg[['Signal ID', 'Address' , 'Timestamp', 'Phase', 'Pedestrian', 'City' , 'Latitude' , 'Longtitude']]
else:
df_agg = df_agg[['Signal ID', 'Address' , 'Timestamp', 'Pedestrian', 'City' , 'Latitude' , 'Longtitude']]
df_agg.reset_index(drop=True, inplace=True) # remove index column
df_agg['Timestamp'] = df_agg['Timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
return df_agg
@st.cache_resource
# Creating combined pie and treemap charts for pedestrian volume analysis
def make_pie_and_bar_chart(df, signals, start_date, end_date, location,Dash_selected , color_map):
if location == 'All':
filter_val = 'all'
col = 'PED'
else:
filter_val = location.split()[-1]
col = 'P'
# Filter the dataframe by the selected signals and date range
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df[(df['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) & (df['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC')) & (df['ADDRESS'].isin(signals))]
# Modify address format in the original dataframe
df_filtered['Address'] = df_filtered['ADDRESS'].str.replace(r'^\d+\s*--\s*', '', regex=True)
# Create a mapping from SIGNAL to the first modified address encountered for each SIGNAL
signal_to_address = df_filtered.groupby('SIGNAL')['Address'].first().to_dict()
else:
df_filtered = df[(df['TIME1'] >= start_date) & (df['TIME1'] <= end_date) & (df['ADDRESS'].isin(signals))]
# Modify address format in the original dataframe
df_filtered['Address'] = df_filtered['ADDRESS'].str.replace(r'^\d+\s*--\s*', '', regex=True)
# Create a mapping from SIGNAL to the first modified address encountered for each SIGNAL
signal_to_address = df_filtered.groupby('SIGNAL')['Address'].first().to_dict()
# Aggregate the data
if location == 'All':
df_agg = df_filtered.groupby(['ADDRESS', 'SIGNAL']).agg({'PED': 'sum','CITY': 'first'}).reset_index()
else:
df_agg = df_filtered[df_filtered['P'] == int(filter_val)].groupby(['ADDRESS', 'SIGNAL']).agg({'PED': 'sum' , 'CITY': 'first'}).reset_index()
# Aggregate the data by signal and sum the pedestrian counts
df_agg1 = df_agg.groupby('SIGNAL').agg({'PED': 'sum'}).reset_index()
df_agg1 = df_agg1.rename(columns={'SIGNAL': 'Signal ID'})
df_agg1['Signal'] = df_agg1['Signal ID'].astype(str)
# Round the pedestrian count to two decimal places
df_agg1['PED'] = df_agg1['PED'].round(0)
df_agg1['Address'] = df_agg1['Signal ID'].map(signal_to_address)
# Create the pie chart
colors = [color_map.get(x, '#000000') for x in df_agg1['Signal ID']]
fig_pie = go.Figure(data=[go.Pie(labels=df_agg1['Signal ID'], values=df_agg1['PED'], name='Signal ID',
marker=dict(colors=colors))])
# Create the treemap figure
marker_colors = df_agg1['Signal ID'].apply(lambda x: color_map.get(x, '#000000'))
fig_treemap = go.Figure(data=go.Treemap(
labels=df_agg1['Signal ID'],
parents=['']*len(df_agg1),
values=df_agg1['PED'],
name='Signal ID',
marker=dict(colors=marker_colors),
customdata=df_agg1['Address'],
hovertemplate='<b>Signal ID:</b> %{label}<br><b>Pedestrian:</b> %{value}<br><b>Address:</b> %{customdata}<extra></extra>',
))
fig_treemap.update_layout(title='Pedestrian Volume by location', showlegend=False)
# Combine the pie, bar, and treemap charts
fig_combined = make_subplots(rows=1, cols=2, specs=[[{'type': 'domain'}, {'type': 'treemap'}]])
fig_combined.add_trace(fig_pie.data[0], row=1, col=1)
fig_combined.add_trace(fig_treemap.data[0], row=1, col=2)
fig_combined.update_layout(showlegend=True , legend_title_text='<b>Location<b>')
fig_combined.update_layout(template='plotly')
fig4 = copy.deepcopy(fig_pie)
fig4.update_layout(
showlegend=True,
legend=dict(title='<b>Location<b>'),
template='plotly'
)
fig4.write_image("fig2.png")
return fig_combined , df_agg1
@st.cache_resource
# Generating hourly average pedestrian volume bar chart with date and location filtering
def make_bar_chart(df, signals, start_date, end_date, location, Dash_selected):
# Convert "TIME1" to datetime and extract the hour and date information
df['Hour'] = pd.to_datetime(df['TIME1']).dt.hour
df['Date'] = pd.to_datetime(df['TIME1']).dt.date
if location == 'All':
filter_val = 'all'
col = 'PED'
else:
filter_val = location.split()[-1]
col = 'P'
# Filter the dataframe by the selected signals and date range
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df[(df['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) &
(df['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC')) &
(df['ADDRESS'].isin(signals))]
else:
df_filtered = df[(df['TIME1'] >= start_date) &
(df['TIME1'] <= end_date) &
(df['ADDRESS'].isin(signals))]
# Aggregate the data
if location == 'All':
df_agg = df_filtered.groupby(['Date', 'Hour']).agg({'PED': 'sum'}).reset_index()
else:
df_agg = df_filtered[df_filtered[col] == int(filter_val)].groupby(['Date', 'Hour']).agg({'PED': 'sum'}).reset_index()
# Calculate the hourly average by dividing the sum of PED by number of days
df_hourly_avg = df_agg.groupby('Hour').agg({'PED': 'mean'}).reset_index()
# Round the pedestrian count to 0 decimal places
df_hourly_avg['PED'] = df_hourly_avg['PED'].round(0)
# Define the data and layout for the bar chart
data = [go.Bar(x=df_hourly_avg['Hour'], y=df_hourly_avg['PED'], text=df_hourly_avg['PED'], texttemplate='%{y:,.0f}', textposition='auto')]
layout = go.Layout(xaxis_title='<b>Hour of the day<b>', yaxis_title='<b>Pedestrian Volume<b>', xaxis=dict(tickmode='linear', dtick=1))
# Create the bar chart
fig_bar = go.Figure(data=data, layout=layout)
fig_bar.update_yaxes(tickformat=".0f")
fig_bar.update_layout(template='plotly')
fig2 = copy.deepcopy(fig_bar)
fig2.update_layout(autosize=False, width=920, height=520)
fig2.update_layout(template='plotly')
fig2.write_image("fig3.png")
return fig_bar, df_hourly_avg
@st.cache_resource
# Creating a bar chart to visualize average pedestrian volume by day of the week
def make_bar_chart2(df, signals, start_date, end_date, location, Dash_selected):
if location == 'All':
filter_val = 'all'
col = 'PED'
else:
filter_val = location.split()[-1]
col = 'P'
# Convert "TIME1" to datetime and extract the day of the week information
df['Day_of_Week'] = pd.to_datetime(df['TIME1']).dt.dayofweek
df['Date'] = pd.to_datetime(df['TIME1']).dt.date
# Filter the dataframe by the selected signals and date range
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df[(df['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) &
(df['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC')) &
(df['ADDRESS'].isin(signals))]
else:
df_filtered = df[(df['TIME1'] >= start_date) &
(df['TIME1'] <= end_date) &
(df['ADDRESS'].isin(signals))]
# Filter based on the location
if location != 'All':
df_filtered = df_filtered[df_filtered[col] == int(filter_val)]
# Group by date and day of the week, then sum the PED values
df_agg = df_filtered.groupby(['Date', 'Day_of_Week']).agg({'PED': 'sum'}).reset_index()
# Group by day of the week and calculate the average pedestrian counts
df_agg2 = df_agg.groupby('Day_of_Week').agg({'PED': 'mean'}).reset_index()
# Round the pedestrian count to 0 decimal places
df_agg2['PED'] = df_agg2['PED'].round(0)
# Create the bar chart
fig_bar = go.Figure(data=[go.Bar(x=df_agg2['Day_of_Week'], y=df_agg2['PED'], showlegend=False , texttemplate='%{y:,.0f}', textposition='auto')])
# Set the x-axis tick labels to the full names of the days of the week
fig_bar.update_layout(xaxis_title='<b>Day of the week<b>', yaxis_title='<b>Pedestrian Volume<b>', showlegend=False)
fig_bar.update_xaxes(tickmode='array', tickvals=[0, 1, 2, 3, 4, 5, 6], ticktext=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
fig_bar.update_yaxes(tickformat=".0f")
fig_bar.update_layout(template='plotly')
fig_bar.update_layout(template='plotly')
fig3 = copy.deepcopy(fig_bar)
fig3.update_layout(autosize=False, width=920, height=520)
fig3.update_layout(template='plotly')
fig3.write_image("fig4.png")
return fig_bar, df_agg2
@st.cache_resource
# Generating a monthly average pedestrian volume bar chart with date and location filtering
def make_bar_chart3(df, signals, start_date, end_date, location, Dash_selected):
if location == 'All':
filter_val = 'all'
col = 'PED'
else:
filter_val = location.split()[-1]
col = 'P'
# Filter the dataframe by the selected signals and date range
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df[(df['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) &
(df['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC')) &
(df['ADDRESS'].isin(signals))]
else:
df_filtered = df[(df['TIME1'] >= start_date) &
(df['TIME1'] <= end_date) &
(df['ADDRESS'].isin(signals))]
# Filter based on the location
if location != 'All':
df_filtered = df_filtered[df_filtered[col] == int(filter_val)]
# Resample to daily frequency and sum the PED counts
df_daily = df_filtered.resample('D', on='TIME1').agg({'PED': 'sum'}).reset_index()
# Extract month and year from the "TIME1" column
df_daily['Month'] = pd.to_datetime(df_daily['TIME1']).dt.month
df_daily['Year'] = pd.to_datetime(df_daily['TIME1']).dt.year
# Group by month and year, and calculate the average of PED
df_agg = df_daily.groupby(['Month']).agg({'PED': 'mean'}).reset_index()
# Group by month and calculate the average pedestrian counts
df_agg2 = df_daily.groupby('Month').agg({'PED': 'mean'}).reset_index()
# Round the pedestrian count to 0 decimal places
df_agg2['PED'] = df_agg2['PED'].round(0)
# Create the bar chart
fig_bar = go.Figure(data=[go.Bar(x=df_agg2['Month'], y=df_agg2['PED'], showlegend=False, texttemplate='%{y:,.0f}', textposition='auto')])
# Set the x-axis tick labels to the full names of the months
fig_bar.update_layout(xaxis_title='<b>Month of the year<b>', yaxis_title='<b>Pedestrian Volume<b>', showlegend=False)
fig_bar.update_xaxes(tickmode='array',
tickvals=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
ticktext=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'])
fig_bar.update_yaxes(tickformat=".0f")
fig_bar.update_layout(template='plotly')
fig8 = copy.deepcopy(fig_bar)
fig8.update_layout(autosize=False, width=920, height=520)
fig8.update_layout(template='plotly')
fig8.write_image("fig5.png")
return fig_bar,df_agg2
@st.cache_resource
# Creating a bar chart for average daily pedestrian volume per signal with color mapping and date/location filters
def make_bar_chart4(df, signals, start_date, end_date, location, Dash_selected, color_map):
# Filter based on location
if location == 'All':
df_filtered = df[df['ADDRESS'].isin(signals)]
else:
filter_val = location.split()[-1]
df_filtered = df[(df['P'] == int(filter_val)) & (df['ADDRESS'].isin(signals))]
# Filter based on date
if Dash_selected == 'Recent data (last 1 year)':
df_filtered = df_filtered[(df_filtered['TIME1'] >= pd.to_datetime(start_date).tz_localize('UTC')) &
(df_filtered['TIME1'] <= pd.to_datetime(end_date).tz_localize('UTC'))]
else:
df_filtered = df_filtered[(df_filtered['TIME1'] >= start_date) & (df_filtered['TIME1'] <= end_date)]
# Aggregate by SIGNAL and Date, summing up the hourly PED values
df_daily_sum = df_filtered.groupby(['SIGNAL', pd.Grouper(key='TIME1', freq='1D')]).agg({'PED': 'sum'}).reset_index()
# Calculate the average daily PED for each SIGNAL
df_agg = df_daily_sum.groupby('SIGNAL').agg({'PED': 'mean'}).reset_index()
# Create the bar chart
fig_bar = go.Figure()
# Only include unique SIGNALs present in the filtered DataFrame, converted to strings
unique_signals = df_agg['SIGNAL'].astype(int).unique()
# Get colors for each signal based on the color map
bar_colors = [color_map[signal] for signal in unique_signals]
# Create the bar chart with colors
fig_bar.add_trace(go.Bar(x=unique_signals, y=df_agg['PED'], marker_color=bar_colors,
texttemplate='%{y:,.0f}', textposition='auto'))
fig_bar.update_xaxes(tickmode='array',
tickvals=unique_signals,
type='category')
fig_bar.update_layout(xaxis_title='<b>Location<b>',
yaxis_title='<b>Pedestrian Volume<b>')
fig_bar.update_yaxes(tickformat=".0f")
fig_bar.update_layout(template='plotly')
fig18 = copy.deepcopy(fig_bar)
fig18.update_layout(autosize=False, width=920, height=520)
fig18.update_layout(template='plotly')
fig18.write_image("fig7.png")
return fig_bar, df_agg
@st.experimental_fragment
def make_map2(df, signals, aggregation_method, location_selected, Dash_selected):
# Check if the 'TIME1' datetime objects are already timezone-aware
if df['TIME1'].dt.tz is not None:
# If they are, convert them to UTC (if they aren't already)
df['TIME1'] = df['TIME1'].dt.tz_convert('UTC')
else:
# If they are timezone-naive, assume they are UTC and localize accordingly
df['TIME1'] = pd.to_datetime(df['TIME1']).dt.tz_localize('UTC')
# Now we have 'TIME1' as timezone-aware in UTC, you can strip the timezone if needed
df['TIME1'] = df['TIME1'].dt.tz_localize(None)
# Determine the date format based on dashboard selection
if Dash_selected == 'Recent data (last 1 year)':
# Moment.js format for date and time
date_format = "YYYY-MM-DD"
# Streamlit time slider for selecting the date range
start_date, end_date = st.slider(
"Select Date Range",
min_value=df['TIME1'].min().to_pydatetime(),
max_value=df['TIME1'].max().to_pydatetime(),
value=(df['TIME1'].min().to_pydatetime(), df['TIME1'].max().to_pydatetime()),
format=date_format
)
# Streamlit slider for selecting the hour range
start_hour, end_hour = st.slider(
"Select Hour Range",
min_value=0,
max_value=23,
value=(0, 23)
)
# Adjust the filter condition for hour range
if start_hour == end_hour:
# Include the entire hour if start and end hours are the same
hour_mask = (df['TIME1'].dt.hour == start_hour)
else:
# Standard range filtering if different start and end hours
hour_mask = (df['TIME1'].dt.hour >= start_hour) & (df['TIME1'].dt.hour <= end_hour)
# Filter by date, hour, selected signals, and location
mask = (df['TIME1'].dt.date >= start_date.date()) & \
(df['TIME1'].dt.date <= end_date.date()) & \
hour_mask & \
(df['ADDRESS'].isin(signals))
if location_selected == 'All':
mask &= df['P'] >= 0 # Include all values of P for intersections
else:
if location_selected.startswith('Phase'):
phase_num = int(location_selected.split()[1])
mask &= df['P'] == phase_num
else:
mask &= df['ADDRESS'] == location_selected
df_filtered = df.loc[mask]
else:
start_date, end_date = st.slider(
"Select Date Range",
min_value=df['TIME1'].min().to_pydatetime(),
max_value=df['TIME1'].max().to_pydatetime(),
value=(df['TIME1'].min().to_pydatetime(), df['TIME1'].max().to_pydatetime()),
format= "YYYY-MM-DD")
mask = (df['TIME1'] >= start_date) & (df['TIME1'] <= end_date) & (df['ADDRESS'].isin(signals))
df_filtered = df.loc[mask]
df_filtered.rename(columns={'LNG': 'LON'}, inplace=True)
# Define and apply aggregation methods
if Dash_selected == 'Recent data (last 1 year)':
aggregation_choices = {
'Average Daily',
'Average Hourly',
'Total'
}
else:
aggregation_choices = {
'Average Daily',
'Total'
}
# Allow the user to select an aggregation method
selected_aggregation = st.selectbox(
"Aggregation method:",
options=list(aggregation_choices),
index=None,
placeholder="Select aggregation method..."
)
if selected_aggregation is not None:
# Determine the appropriate aggregation function and grouping based on the selected aggregation method
if selected_aggregation == 'Average Daily':
# Group by location, signal, and day, then sum the PEDs for each day
daily_sum = df_filtered.groupby(['LAT', 'LON', 'ADDRESS', 'SIGNAL', pd.Grouper(key='TIME1', freq='1D')]).agg({'PED': 'sum'}).reset_index()
# Now group by location and signal (without the day) to calculate the average of these daily sums
df_agg = daily_sum.groupby(['LAT', 'LON', 'ADDRESS', 'SIGNAL']).agg({'PED': 'mean'}).reset_index()
elif selected_aggregation == 'Average Hourly' and Dash_selected == 'Recent data (last 1 year)':
hourly_sum = df_filtered.groupby(['LAT', 'LON', 'ADDRESS', 'SIGNAL', pd.Grouper(key='TIME1', freq='1H')]).agg({'PED': 'sum'}).reset_index()
df_agg = hourly_sum.groupby(['LAT', 'LON', 'ADDRESS', 'SIGNAL']).agg({'PED': 'mean'}).reset_index()
elif selected_aggregation == 'Total':
df_agg = df_filtered.groupby(['LAT', 'LON', 'ADDRESS', 'SIGNAL']).agg({'PED': 'sum'}).reset_index()
# Create color map
unique_signals = df['SIGNAL'].unique().tolist()
mean_lat = df['LAT'].mean()
mean_lng = df['LNG'].mean()
# Create a Folium map with specified width and height
m = folium.Map(location=[mean_lat, mean_lng], zoom_start=13, tiles=None)
# Add custom tile layers
pedat_tiles = folium.TileLayer(
tiles='https://api.mapbox.com/styles/v1/bashasvari/clwb9hhew005201pp36qd2b8y/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYmFzaGFzdmFyaSIsImEiOiJjbGVmaTdtMmIwcXkzM3Jxam9hb2pwZ3BoIn0.JmYank8e3bmQ7RmRiVdTIg',
attr='PEDAT map',
name='PEDAT',
overlay=False,
control=True
)
satellite = folium.TileLayer(
tiles='https://api.mapbox.com/styles/v1/bashasvari/cluvp5mkm000i01og0rbcgwmf/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYmFzaGFzdmFyaSIsImEiOiJjbGVmaTdtMmIwcXkzM3Jxam9hb2pwZ3BoIn0.JmYank8e3bmQ7RmRiVdTIg',
attr='Satellite',
name='Satellite Map',
overlay=False,
control=True
)
# Add the PEDAT layer and show it by default
pedat_tiles.add_to(m)
satellite.add_to(m)
# Adding other tile layers but not showing them by default
folium.TileLayer('OpenStreetMap', name='Open Street Map', overlay=False, control=True).add_to(m)
folium.TileLayer('CartoDB dark_matter', name='CartoDB Dark Matter', overlay=False, control=True).add_to(m)
# Get the colormap object based on user selection
max_ped = df_agg['PED'].max()
min_ped = df_agg['PED'].min()
colormap = cm.linear.Spectral_04.scale(min_ped, max_ped)
colormap.caption = 'Pedestrian Count'
colormap.add_to(m)
if selected_aggregation == 'Average Daily':
# Constants for scaling
base_radius = 4 # This is the base size for circles
scale_factor = 0.04 # This factor will scale the transformation to appropriate map units
# Square root scaling
df_agg['Scaled_RADIUS'] = df_agg['PED'] * scale_factor
elif selected_aggregation == 'Average Hourly':
# Constants for scaling
base_radius = 4 # This is the base size for circles
scale_factor = 2 # This factor will scale the transformation to appropriate map units
# Square root scaling
df_agg['Scaled_RADIUS'] = np.sqrt(df_agg['PED']) * scale_factor
elif selected_aggregation == 'Total':
# Constants for scaling
base_radius = 4 # This is the base size for circles
scale_factor = 0.04 # This factor will scale the transformation to appropriate map units
# Square root scaling
df_agg['Scaled_RADIUS'] = np.sqrt(df_agg['PED']) * scale_factor
# Adding circles with scaled radii
for idx, row in df_agg.iterrows():
folium.CircleMarker(
location=[row['LAT'], row['LON']],
radius=max(base_radius, row['Scaled_RADIUS']), # Ensure a minimum size for visibility
popup=folium.Popup(f"<div style='width:250px;'><strong>Address:</strong><br>{row['ADDRESS']}<br><strong>Pedestrian Count:</strong><br>{round(row['PED'],0):,.0f}</div>", max_width=250),
color=colormap(row['PED']),
fill=True,
fill_opacity=0.7,
fill_color=colormap(row['PED'])
).add_to(m)
folium.LayerControl().add_to(m)
st_folium(m, width='80%', height=600)
# Define the Streamlit app
def main():
# Set the app title
st.set_page_config(page_title='PEDAT Dashboard' , page_icon="📈" , layout="wide" )
# Add a title to the sidebar
st.title("Pedestrian Volume in Utah")
st.markdown(text1)
st.markdown(text2)
# Display UDOT logo in the sidebar
udot_path = 'images/UDOT.png'
st.sidebar.image(udot_path , width=265)
st.sidebar.write("")
# Display USU in the sidebar
logo_path = 'images/logo-1.png'
st.sidebar.image(logo_path , width=240)
st.sidebar.markdown(f'[**Singleton Transportation Lab**](https://engineering.usu.edu/cee/research/labs/patrick-singleton/index)')
expander2 = st.sidebar.expander("**How to use**")
with expander2:
expander2.write('''
First, use the map to select or search for specific location(s) with available data. Second, a particular type of data (recent or historical). Third, select parameters (dates, location and time units). Fourth, view the results as averages, figures, a map, data, or a report.
''')
expander2.write(f'[**PEDAT User Guide**](https://usu-my.sharepoint.com/:b:/g/personal/a02347157_aggies_usu_edu/EYhhPdO6z_9IlPW7244qu9AB3Mot2-VnZxFKpyQG81UiTQ?e=2HMmlV)')
st.sidebar.markdown("[Step 1: Select location(s)](#step-1-select-data-type-and-location-s)")
st.subheader('Step 1: Select data type and location(s)')
st.markdown(
"""<style>
div[class*="stSelectbox"] > label > div[data-testid="stMarkdownContainer"] > p {
font-size: 16px;
}
</style>
""", unsafe_allow_html=True)
# Read the data
df3 = pd.read_json('data/updated_mapdata.json')
selected_data = df3
# Check if the list is empty before accessing it
mean_lat = selected_data['LAT'].mean()
mean_lng = selected_data['LON'].mean()
df3 = selected_data
a = df3['ADDRESS'].tolist()
default_address = [a[1]]
# Create a custom TileLayer
pedat_tiles = folium.TileLayer(
tiles='https://api.mapbox.com/styles/v1/bashasvari/clwb9hhew005201pp36qd2b8y/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYmFzaGFzdmFyaSIsImEiOiJjbGVmaTdtMmIwcXkzM3Jxam9hb2pwZ3BoIn0.JmYank8e3bmQ7RmRiVdTIg',
attr='PEDAT map',
name='PEDAT',
overlay=False,
control=True
)
Satellite = folium.TileLayer(
tiles='https://api.mapbox.com/styles/v1/bashasvari/cluvp5mkm000i01og0rbcgwmf/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYmFzaGFzdmFyaSIsImEiOiJjbGVmaTdtMmIwcXkzM3Jxam9hb2pwZ3BoIn0.JmYank8e3bmQ7RmRiVdTIg',
attr='Satellite',
name='Satellite Map',
overlay=False,
control=True
)
# Create the map with PEDAT as the default visible layer
m = folium.Map(location=[mean_lat, mean_lng], zoom_start=8, tiles=None)
# Add the PEDAT layer and show it by default
pedat_tiles.add_to(m)
Satellite.add_to(m)
# Adding other tile layers but not showing them by default
folium.TileLayer('OpenStreetMap', name='Open Street Map', overlay=False, control=True).add_to(m)
folium.TileLayer('CartoDB dark_matter', name='CartoDB Dark Matter', overlay=False, control=True).add_to(m)
# Convert dataFrame to GeoJSON format
geo_data = df3[["LAT", "LON", "ADDRESS"]].copy()
def feature_from_row(row):
return {
"type": "Feature",
"properties": {"address": row["ADDRESS"]},
"geometry": {
"type": "Point",
"coordinates": [row["LON"], row["LAT"]]
}
}
geo_json = {
"type": "FeatureCollection",
"features": geo_data.apply(feature_from_row, axis=1).tolist()
}
# Create the invisible GeoJson layer for search functionality
geo_layer = folium.GeoJson(geo_json ,
marker=folium.CircleMarker(radius=0.00000000000000000001, color=None ,opacity=7), control=False).add_to(m)
search = Search(
layer=geo_layer,
geom_type="Point",
placeholder="Search for an address/signals",
collapsed=True,
search_label="address"
).add_to(m)
# Define a style function for the GeoJson layer
region_colors = {
"Region 1": "red",
"Region 2": "green",
"Region 3": "blue",
"Region 4": "purple"
}
def style_function(feature):
region_name = feature['properties']['NAME']
return {
'color': region_colors.get(region_name, 'black'), # Default to black if the region is not found
'weight': 1,
'fillOpacity': 0.05
}
# Add all regions as a single GeoJson layer
geojson_path = "data/UDOT_Regions.geojson"
with open(geojson_path) as f:
geojson_data = json.load(f)
def popup_function(feature):
region_name = feature['properties']['NAME']
return folium.Popup(f"<div style='width: 200px;'><strong>{region_name}</strong></div>", max_width=250)
# Create a GeoJson layer with popups
regions_layer = folium.GeoJson(
geojson_data,
name='UDOT Regions',
style_function=style_function,
popup=folium.GeoJsonPopup(fields=['NAME'], aliases=[''], labels=True, style='font-size: 12px'),
show=False # Ensure the layer is initially hidden
)
regions_layer.add_to(m)
df3['Address'] = df3['ADDRESS'].str.replace(r'^\d+\s*--\s*', '', regex=True)
# Add custom icons
callback = """
function (row) {
var icon, marker, popupContent;
icon = L.AwesomeMarkers.icon({
icon: 'fa-traffic-light',
prefix: 'fa',
});
marker = L.marker(new L.LatLng(row[0], row[1]), {icon: icon});
popupContent = '<b>Signal ID:</b> ' + row[3] + '<br>' + '<b>Address:</b> ' + row[2];
marker.bindPopup(popupContent, {maxWidth: 300, minWidth: 150});
return marker;
};
"""
# Prepare your data list, with latitude, longitude, and popup content (address)
data = list(zip(df3['LAT'], df3['LON'], df3['Address'] , df3['SIGNAL']))
# Use FastMarkerCluster with the callback
FastMarkerCluster(data=data, callback=callback , control=False).add_to(m)
Draw(
export=False,
filename="my_data.geojson",
position="topleft",
draw_options={
'circle': False,
'circlemarker': False,
'marker': False,
'polyline': False
}
).add_to(m)
address = []
# Fit the map bounds to show all points
sw = df3[['LAT', 'LON']].min().values.tolist()
ne = df3[['LAT', 'LON']].max().values.tolist()
m.fit_bounds([sw, ne])
if 'selected_addresses' not in st.session_state:
st.session_state.selected_addresses = []
# Render the map using st_folium
folium.LayerControl().add_to(m)
s = st_folium(m, width='80%', height=600, returned_objects=["last_object_clicked", "last_active_drawing"])
# Function to add or update the selected addresses based on map interaction
def add_selected_address(lat, lng, polygon=None):
if polygon is not None:
for index, row in df3.iterrows():
point = Point(row['LON'], row['LAT'])
if polygon.contains(point) and row['ADDRESS'] not in st.session_state.selected_addresses:
st.session_state.selected_addresses.append(row['ADDRESS'])
else:
filtered_df = df3[(df3['LAT'] == lat) & (df3['LON'] == lng)]
for index, row in filtered_df.iterrows():
if row['ADDRESS'] not in st.session_state.selected_addresses:
st.session_state.selected_addresses.append(row['ADDRESS'])
# Check if a location or a polygon has been selected on the map
if s is not None:
if "last_object_clicked" in s and s["last_object_clicked"] is not None:
json_obj = s["last_object_clicked"]
add_selected_address(json_obj["lat"], json_obj["lng"])
elif "last_active_drawing" in s and s["last_active_drawing"] is not None:
polygon_coords = s["last_active_drawing"]["geometry"]["coordinates"]
polygon = Polygon(polygon_coords[0])
add_selected_address(None, None, polygon)
selected_signals = []
# Ensure 'selected_signals' is initialized in session_state
if 'selected_signals' not in st.session_state:
st.session_state.selected_signals = []
# Form for finalizing the selection of addresses
with st.form("selected_locations_form"):
if not st.session_state.selected_addresses:
st.write('')
else:
st.write("**Review and select the locations**")
# List to store the state of each checkbox
checkbox_states = []
# Dynamically create a checkbox for each selected address
for address in st.session_state.selected_addresses:
checkbox_state = st.checkbox(address, key=address, value=True)
checkbox_states.append(checkbox_state)
# Conditionally display the dropdown if any address is selected
if any(checkbox_states):
dash = ['Recent data (last 1 year)', 'Historical data (last 5 years)']
Dash_selected = st.selectbox('**Select data type**', options=dash)
else:
# Prompt user if no address is checked
st.warning("Please select at least one address to proceed.")
# Submit button for the form
submitted = st.form_submit_button("Submit")
if submitted:
# Filter the selected addresses based on checkboxes that are ticked
selected_signals = [address for address, checked in zip(st.session_state.selected_addresses, checkbox_states) if checked]
st.session_state.selected_signals = selected_signals
if st.session_state.selected_signals:
job_config = bigquery.QueryJobConfig(
query_parameters=[
bigquery.ArrayQueryParameter(
"selected_signals", "STRING", st.session_state.selected_signals
)
]
)
# Use an appropriate SQL query based on the data type selected
if Dash_selected == 'Recent data (last 1 year)':
df = client.query(sql_query2, job_config=job_config).to_dataframe()
else:
df = client.query(sql_query3, job_config=job_config).to_dataframe()
df['TIME1'] = pd.to_datetime(df['TIME1'])
# Extract unique signals and create color maps
unique_signals = df['SIGNAL'].unique().tolist()
color_map = create_color_map(unique_signals)
# Assuming df3 is defined elsewhere and contains 'ADDRESS'
all_addresses = df3['ADDRESS'].tolist()