-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex_old.html
2590 lines (2216 loc) · 145 KB
/
index_old.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>stlite app</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.css"
/>
</head>
<body>
<div id="root"></div>
<script src="https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.js"></script>
<script>
stlite.mount(
{
requirements: ["unidecode", "openpyxl", "plotly"],
entrypoint: "streamlit_app.py",
files: {
"streamlit_app.py": `import streamlit as st
import json
import pyodide.http
from PIL import Image
from io import BytesIO
############################################
from functions import load_url, load_settings, load_page_setup, load_sidebar_image, load_colourblind_checkbox, load_plotting_checkbox, load_datatable_checkbox
############################################
def initialise_session_state():
state_variables = ['current_page', 'settings',
'current_page','current_site','current_site_data', 'site_trend_data', 'site_raw_data',
'filtered_state_data','filtered_trend_data',
'sidebar_image','data_table_mode',
'filtered_sites','site_user_choice',
'colourblind_mode','colourblind_colours',
'second_site','site2_user_choice','site2_data',
'reverse_2nd_axis','log_check','log_check_trend', 'include_trend_scatter']
for variable_i in state_variables:
if variable_i not in st.session_state:
st.session_state[variable_i] = None
dict_variables = ['full_state_data','full_trend_data',]
for variable_j in dict_variables:
if variable_j not in st.session_state:
st.session_state[variable_j] = {}
true_variables = ['plot_mode']
for variable_j in true_variables:
if variable_j not in st.session_state:
st.session_state[variable_j] = True
############################################
load_page_setup()
#initialise session state
initialise_session_state()
#load sidebar
if not st.session_state['sidebar_image']:
await load_sidebar_image()
st.sidebar.image(Image.open(BytesIO(st.session_state['sidebar_image'])))
#load settings
if not st.session_state['settings']:
await load_settings()
#load colourblind checkbox
load_colourblind_checkbox()
#load plotting checkbox
load_plotting_checkbox()
#load datatable checkbox
load_datatable_checkbox()
#text
st.title('Welcome to State View')
st.write('To get started, choose a page on the sidebar.')
st.write('---')
st.title('DISCLAIMER')
st.write('''
The enclosed information is supplied, within the framework of our quality system, from the best data currently available.
However, as we endeavour to continuously improve our products, we reserve the right to amend the data on which this information is based, where necessary and without notice, at any time. As a result, the information supplied to you now may not be the same as that subsequently produced for you or any other client.
While Manawatū-Whanganui Regional Council has exercised all reasonable skill and care in controlling the contents of the information, you should independently check the information provided if the accuracy of that information is important to you.
Under no circumstances will the Manawatū-Whanganui Regional Council or its employees or agents be liable in contract, tort or otherwise to compensate you for any loss, injury or damage (including loss of profits or consequential loss) arising directly or indirectly from the supply by the Council or its agents of inadequate, inaccurate or incorrect information.
Manawatū-Whanganui Regional Council is the owner of the copyright subsisting in the enclosed material unless otherwise specified. Copies of the enclosed material, or any part thereof, by any means whatsoever shall be made only for use by you as the client for your own internal purposes and shall not be conveyed to any third party or merged into another machine readable database without the express permission of the Council.
Any use of the material supplied, for example, by inclusion in a report or a media release, should be accompanied by an acknowledgment of the source of the data.
Your acceptance of the enclosed material and/or services signifies your acceptance of these terms and conditions.
''')
############################################
`,
"functions.py": `import streamlit as st
import json
import pyodide.http
from PIL import Image
from io import BytesIO
##########################################
##########################################
##########################################
def load_page_setup():
#load the page config
st.set_page_config(
page_title="State View",
layout="wide",
initial_sidebar_state="expanded"
)
def load_colourblind_checkbox():
colourblind_check = st.sidebar.checkbox('Use colourblind mode',value = st.session_state['colourblind_mode'])
if colourblind_check:
st.session_state['colourblind_colours'] = st.session_state['settings'].get('nof_grade_colourblind_colours')
st.session_state['colourblind_mode'] = True
else:
st.session_state['colourblind_colours'] = st.session_state['settings'].get('nof_grade_colours')
st.session_state['colourblind_mode'] = False
def load_plotting_checkbox():
colourblind_check = st.sidebar.checkbox('Plot figures?',value = st.session_state['plot_mode'])
if colourblind_check:
st.session_state['plot_mode'] = True
else:
st.session_state['plot_mode'] = False
def load_datatable_checkbox():
colourblind_check = st.sidebar.checkbox('Show data table?',value = st.session_state['data_table_mode'])
if colourblind_check:
st.session_state['data_table_mode'] = True
else:
st.session_state['data_table_mode'] = False
def load_second_site_checkbox():
second_site = st.checkbox('Compare a second site?',value = st.session_state['second_site'])
if second_site:
st.session_state['second_site'] = True
else:
st.session_state['second_site'] = False
def load_reverse_second_axis_checkbox():
second_axis = st.checkbox('Reverse the second axis?',value = st.session_state['reverse_2nd_axis'])
if second_axis:
st.session_state['reverse_2nd_axis'] = True
else:
st.session_state['reverse_2nd_axis'] = False
def load_log_checkbox():
log_check = st.checkbox('Plot the y-axis on a log scale?',value = st.session_state['log_check'],key='logcheck')
if log_check:
st.session_state['log_check'] = True
else:
st.session_state['log_check'] = False
def load_log_checkbox_trend():
log_check = st.checkbox('Plot the y-axis on a log scale?',value = st.session_state['log_check_trend'],key='logchecktrend')
if log_check:
st.session_state['log_check_trend'] = True
else:
st.session_state['log_check_trend'] = False
##########################################
##########################################
##########################################
async def load_url(url,text=True):
response = await pyodide.http.pyfetch(url)
if text:
data = await response.string()
else:
data = await response.bytes()
return data
##########################################
##########################################
##########################################
async def load_sidebar_image():
url = r'https://raw.githubusercontent.com/lukefullard/State_and_Trends_Reporting/main/assets/SidebarTitle.png'
sidebar_image = await load_url(url,text=False)
st.session_state['sidebar_image'] = sidebar_image
##########################################
##########################################
##########################################
async def load_settings():
url = r'https://raw.githubusercontent.com/lukefullard/State_and_Trends_Reporting/main/scripts_and_settings/app_settings.json'
data = await load_url(url,text=True)
st.session_state['settings'] = json.loads(data)
##########################################
##########################################
##########################################
def clean_text(text, add_hash = False):
'''
Convenience function to clean text by removing unicode characters (such as macrons) and non-alpha-numeric characters (spaces, punctuation, symbols etc)
Parameters
----------
text : string
DESCRIPTION: String to clean
add_hash : Boolean, optional
DESCRIPTION: The default is False. If True, adds an underscore + a hash to the text (to ensure uniqueness after cleaning).
Returns
-------
cleaned_text : string
DESCRIPTION: cleaned string
'''
import unidecode
cleaned_text = unidecode.unidecode(text)
cleaned_text = ''.join(e for e in cleaned_text if e.isalnum())
if add_hash:
import hashlib
cleaned_text = cleaned_text + '_' + str(hashlib.shake_256(text.encode()).hexdigest(5))
return cleaned_text
##########################################
##########################################
##########################################
def get_data_links(topic = 'Rivers', site2 = False):
if site2:
cleaned_site_name = clean_text(st.session_state['site2_user_choice'], add_hash = True)
state_data_link = st.session_state['settings'].get('state_data') + f'{topic}/' +cleaned_site_name + '.xlsx'
trend_data_link = st.session_state['settings'].get('trend_data') + f'{topic}/' +cleaned_site_name + '.xlsx'
raw_data_link = st.session_state['settings'].get('raw_data') + topic + '/' + cleaned_site_name + '.xlsx'
else:
cleaned_site_name = clean_text(st.session_state['site_user_choice'], add_hash = True)
state_data_link = st.session_state['settings'].get('state_data') + f'{topic}/' +cleaned_site_name + '.xlsx'
trend_data_link = st.session_state['settings'].get('trend_data') + f'{topic}/' +cleaned_site_name + '.xlsx'
raw_data_link = st.session_state['settings'].get('raw_data') + topic + '/' + cleaned_site_name + '.xlsx'
return state_data_link,raw_data_link, trend_data_link
##########################################
##########################################
##########################################
def get_full_state_links(topic = 'Rivers'):
return st.session_state['settings'].get('state_data') + topic + '.xlsx'
def get_full_trend_links(topic = 'Rivers'):
return st.session_state['settings'].get('trend_data') + topic + '.xlsx'
##########################################
##########################################
##########################################
##########################################
##########################################
##########################################`,
"plotting_functions.py": `import streamlit as st
import copy
import pandas as pd
def grade_time_plot(data,topic='Rivers'):
year_list = sorted(list(data['year range'].unique()))
first_year = int(year_list[0][0:4])
last_year = int(year_list[-1][0:4])
final_year_list = [f"{x} - {x+4}" for x in range(first_year,last_year+1)]
#st.write(final_year_list)
copydata = copy.deepcopy(data)
copydata = copydata.sort_values(by = ['year range','attribute type'],ascending = True)
import plotly.express as px
fig = px.scatter(copydata, x='year range', y='attribute type', color="NOF_Grade",
hover_data="NOF_Grade", text = "NOF_Grade",
color_discrete_map = st.session_state['colourblind_colours'],
category_orders={"NOF_Grade": list(st.session_state['colourblind_colours'].keys()),
"year range": final_year_list
},
title = f"{st.session_state['current_site']}",
)
fig.update_traces(marker_size = st.session_state['settings'].get('plot_settings').get('grade_time_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
marker_symbol = st.session_state['settings'].get('plot_settings').get('basic_marker_shape'),)
fig.update_layout(yaxis_title='')
fig.update_layout(xaxis_title='')
fig.update_layout(legend_title_text='')
attributes = sorted(list(copydata['attribute type'].unique()))
final_attributes = [x for x in attributes if x in st.session_state['settings'].get('nof_band_definitions').get(topic).keys()]
fig.update_yaxes(categoryorder='array', categoryarray=final_attributes )
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
return fig
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
def grade_time_plot_2_sites(data1,data2,topic='Rivers'):
final_data = copy.deepcopy(data2)
final_data = pd.concat([final_data,data1],ignore_index = True).reset_index(drop=True)
year_list = sorted(list(final_data['year range'].unique()))
first_year = int(year_list[0][0:4])
last_year = int(year_list[-1][0:4])
final_year_list = [f"{x} - {x+4}" for x in range(first_year,last_year+1)]
copydata = copy.deepcopy(final_data)
copydata = copydata.sort_values(by = ['year range','attribute type'],ascending = True)
import plotly.express as px
fig = px.scatter(copydata, x='year range', y='attribute type', color="NOF_Grade",
hover_data="NOF_Grade", text = "NOF_Grade",
color_discrete_map = st.session_state['colourblind_colours'],
category_orders={"NOF_Grade": list(st.session_state['colourblind_colours'].keys()),
"year range": final_year_list,
"site name": [st.session_state['site_user_choice'],st.session_state['site2_user_choice']]
},
#title = f"{st.session_state['current_site']}",
facet_col="site name"
)
if st.session_state['reverse_2nd_axis']:
fig.update_xaxes(matches=None)
fig.update_xaxes(categoryarray = list(reversed(final_year_list)),categoryorder = "array",col = 2)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_annotations(font=dict(size=st.session_state['settings'].get('plot_settings').get('grade_time_font_size'),
color=st.session_state['settings'].get('plot_settings').get('font_colour')))
fig.update_traces(marker_size = st.session_state['settings'].get('plot_settings').get('grade_time_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
marker_symbol = st.session_state['settings'].get('plot_settings').get('basic_marker_shape'),)
fig.update_layout(yaxis_title='')
fig.update_layout(xaxis_title='')
fig.update_layout(legend_title_text='')
attributes = sorted(list(copydata['attribute type'].unique()))
final_attributes = [x for x in attributes if x in st.session_state['settings'].get('nof_band_definitions').get(topic).keys()]
fig.update_yaxes(categoryorder='array', categoryarray=final_attributes )
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
return fig
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
def scatter_plot(data, attribute_name, data_column = 'Median',topic='Rivers', sitename = st.session_state['current_site'], markersymbol = 'triangle-up'):
year_list = sorted(list(data['year range'].unique()))
first_year = int(year_list[0][0:4])
last_year = int(year_list[-1][0:4])
final_year_list = [f"{x} - {x+4}" for x in range(first_year,last_year+1)]
copydata = copy.deepcopy(data)
copydata = copydata.sort_values(by = ['year range','attribute type'],ascending = True)
if st.session_state['log_check']:
min_y = 0.975*min(copydata[data_column])
else:
min_y = 0
max_y = 1.025*max(copydata[data_column])
import plotly.express as px
fig = px.scatter(copydata, x='year range', y=data_column,
color="site name",
hover_data="NOF_Grade", text = "NOF_Grade",
title = sitename,
color_discrete_map = {sitename: "black"},
log_y = st.session_state['log_check'],
range_y = [min_y,max_y],
)
fig.update_traces(marker_size = st.session_state['settings'].get('plot_settings').get('scatter_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
marker_symbol = markersymbol,
textfont_color = st.session_state['settings'].get('plot_settings').get('scatter_font_colour'))
fig.update_layout(yaxis_title=f"{attribute_name} ({st.session_state['settings'].get('nof_attribute_statistics').get(attribute_name)}, {st.session_state['settings'].get('nof_attribute_units').get(attribute_name)})")
fig.update_layout(xaxis_title='')
fig.update_layout(legend_title_text='')
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
#adding background colours
if (st.session_state['settings'].get('add_nof_grade_background_colours')) and (st.session_state['settings'].get('nof_band_definitions').get(topic).get(attribute_name)):
current_band_definitions = st.session_state['settings'].get('nof_band_definitions').get(topic).get(attribute_name)
for iter_j,label_j in enumerate(current_band_definitions.get('labels')):
current_colour = st.session_state['colourblind_colours'].get(label_j)
y0 = current_band_definitions.get('bins')[iter_j]
y1 = min(current_band_definitions.get('bins')[iter_j+1], 1.025*max(copydata[data_column]))
fig.add_hrect(y0=y0, y1=y1, line_width=0, fillcolor=current_colour, opacity=0.4)
#adding custom legend
import plotly.graph_objects as go
if not topic == "Contact Rec":
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="A",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('A'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="B",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('B'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="C",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('C'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="D",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('D'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
if "E coli" in attribute_name:
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="E",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('E'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
return fig
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
def scatter_plot_2variables(data, attribute_name1,attribute_name2, data_column1 = 'Median',data_column2 = 'Median',topic='Rivers', sitename = st.session_state['current_site'], markersymbol1 = 'triangle-up', markersymbol2 = 'triangle-down'):
year_list = sorted(list(data['year range'].unique()))
first_year = int(year_list[0][0:4])
last_year = int(year_list[-1][0:4])
final_year_list = [f"{x} - {x+4}" for x in range(first_year,last_year+1)]
final_data_column = []
for iter_j,row_j in data.iterrows():
if row_j['attribute type'] == attribute_name1:
final_data_column.append(row_j[data_column1])
if row_j['attribute type'] == attribute_name2:
final_data_column.append(row_j[data_column2])
data['final_data_column'] = final_data_column
copydata = copy.deepcopy(data)
copydata = copydata.sort_values(by = ['year range','attribute type'],ascending = True)
if st.session_state['log_check']:
min_y = 0.975*min(copydata['final_data_column'])
else:
min_y = 0
max_y = 1.025*max(copydata['final_data_column'])
import plotly.express as px
fig = px.scatter(copydata, x='year range', y='final_data_column',
color="site name",
hover_data="NOF_Grade", text = "NOF_Grade",
title = f"{sitename}: {attribute_name1} -- and -- {attribute_name2}",
color_discrete_map = {sitename: "black"},
log_y = st.session_state['log_check'],
range_y = [min_y,max_y],
symbol = "attribute type",
symbol_map = {attribute_name1: markersymbol1, attribute_name2: markersymbol2},
category_orders={
"year range": final_year_list,
},
)
fig.update_traces(marker_size =st.session_state['settings'].get('plot_settings').get('scatter_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
textfont_color = st.session_state['settings'].get('plot_settings').get('scatter_font_colour'))
fig.update_layout(yaxis_title='')
fig.update_layout(xaxis_title='')
fig.update_layout(legend_title_text='')
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
return fig
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
def scatter_plot_2_sites(data0,data1,
attribute_name0, attribute_name1,
data_column0 = 'Median', data_column1 = 'Median',topic='Rivers',
sitename0 = '', sitename1 = '',
markersymbol0 = 'triangle-up', markersymbol1 = 'triangle-down'):
data0['final_data_column'] = data0[data_column0]
data1['final_data_column'] = data1[data_column1]
final_data = copy.deepcopy(data0)
final_data = pd.concat([final_data,data1],ignore_index = True).reset_index(drop=True)
year_list = sorted(list(final_data['year range'].unique()))
first_year = int(year_list[0][0:4])
last_year = int(year_list[-1][0:4])
final_year_list = [f"{x} - {x+4}" for x in range(first_year,last_year+1)]
copydata = copy.deepcopy(final_data)
copydata = copydata.sort_values(by = ['year range'],ascending = True)
if st.session_state['log_check']:
min_y = 0.975*min(copydata['final_data_column'])
else:
min_y = 0
max_y = 1.025*max(copydata['final_data_column'])
import plotly.express as px
fig = px.scatter(copydata, x='year range', y='final_data_column',
color="site name",
hover_data="NOF_Grade", text = "NOF_Grade",
symbol = "site name",
title = f"{sitename0} ({attribute_name0}) -- and -- {sitename1} ({attribute_name1})",
color_discrete_map = {sitename0: "black",sitename1: "black"},
symbol_map = {sitename0: markersymbol0, sitename1: markersymbol1},
log_y = st.session_state['log_check'],
range_y = [min_y,max_y],
category_orders={
"year range": final_year_list,
},
)
fig.update_traces(marker_size =st.session_state['settings'].get('plot_settings').get('scatter_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
#marker_symbol = markersymbol,
textfont_color = st.session_state['settings'].get('plot_settings').get('scatter_font_colour'))
if attribute_name0 == attribute_name1:
fig.update_layout(yaxis_title=f"{attribute_name0} ({st.session_state['settings'].get('nof_attribute_statistics').get(attribute_name0)}, {st.session_state['settings'].get('nof_attribute_units').get(attribute_name0)})")
else:
fig.update_layout(yaxis_title="")
fig.update_layout(xaxis_title='')
fig.update_layout(legend_title_text='')
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
#adding background colours
if attribute_name0 == attribute_name1:
if (st.session_state['settings'].get('add_nof_grade_background_colours')) and (st.session_state['settings'].get('nof_band_definitions').get(topic).get(attribute_name0)):
current_band_definitions = st.session_state['settings'].get('nof_band_definitions').get(topic).get(attribute_name0)
for iter_j,label_j in enumerate(current_band_definitions.get('labels')):
current_colour = st.session_state['colourblind_colours'].get(label_j)
y0 = current_band_definitions.get('bins')[iter_j]
y1 = min(current_band_definitions.get('bins')[iter_j+1], 1.025*max(copydata['final_data_column']))
fig.add_hrect(y0=y0, y1=y1, line_width=0, fillcolor=current_colour, opacity=0.4)
#adding custom legend
import plotly.graph_objects as go
if not topic == "Contact Rec":
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="A",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('A'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="B",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('B'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="C",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('C'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="D",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('D'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
if "E coli" in attribute_name0:
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name="E",
marker=dict(size=7, color=st.session_state['colourblind_colours'].get('E'), symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
return fig
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
def time_series_scatter_plot(data, variable_name, variable_units, trend_period, trend_text = '', data_column = 'Value', date_column = 'date time',topic='Rivers', sitename = st.session_state['current_site'], markersymbol = 'triangle-up',censored_markersymbol = 'hexagon2', marker_colour = '#86dcd5',censored_marker_colour = '#fa6e75',
plot_trend=False, trend_dates = None, trend_data = None, trend_lci = None, trend_uci = None):
copydata = copy.deepcopy(data)
#deal with censored values
raw_value = []
censored = []
marker_ = []
marker_colour_ = []
for iter_q,row_q in copydata.iterrows():
if str(row_q[data_column][0]) in ['<','>']:
raw_value.append(float(str(row_q[data_column][1:])))
censored.append(True)
marker_.append(censored_markersymbol)
marker_colour_.append(censored_marker_colour)
else:
raw_value.append(float(row_q[data_column]))
censored.append(False)
marker_.append(markersymbol)
marker_colour_.append(marker_colour)
copydata['raw_value'] = raw_value
copydata['censored'] = censored
copydata['marker_symbol'] = marker_
copydata['marker_colour'] = marker_colour_
if st.session_state['log_check_trend']:
copydata = copydata.loc[copydata['raw_value'] > 0.].reset_index(drop=True)
min_y = 0.975*min(copydata['raw_value'])
else:
min_y = 0
max_y = 1.025*max(copydata['raw_value'])
import plotly.express as px
fig = px.scatter(copydata, x=date_column, y='raw_value',
color="marker_colour",
color_discrete_map ={marker_colour:marker_colour,censored_marker_colour:censored_marker_colour},
symbol_map ={censored_markersymbol:censored_markersymbol,markersymbol:markersymbol},
symbol = "marker_symbol",
hover_data=[data_column, "censored"],
title = sitename,
log_y = st.session_state['log_check_trend'],
range_y = [min_y,max_y],
)
fig.update_traces(marker_size =st.session_state['settings'].get('plot_settings').get('time_series_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
textfont_color = st.session_state['settings'].get('plot_settings').get('scatter_font_colour'))
fig.update_layout(yaxis_title=f"{variable_name} [{variable_units}]")
fig.update_layout(xaxis_title='date')
fig.update_layout(legend_title_text='')
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
fig.update_layout(showlegend=False)
#add trend if present
if plot_trend:
import plotly.graph_objects as go
fig.add_trace(go.Scatter(x=trend_dates, y=trend_data,
mode='lines',
name='lines',
line = dict(color='black', width=4)))
fig.add_trace(go.Scatter(x=trend_dates, y=trend_lci,
mode='lines',
name='lines',
line = dict(color='orange', width=2, dash='dash')))
fig.add_trace(go.Scatter(x=trend_dates, y=trend_uci,
mode='lines',
name='lines',
line = dict(color='orange', width=2, dash='dash')))
fig.update_layout(
title=f"{sitename} : with {trend_period} year trend ({trend_text})",)
return fig
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
###########################################
def trend_classification_plot(data,topic='Rivers',marker = 'square'):
copydata = copy.deepcopy(data)
copydata['marker_colour'] = copydata["confidence of improving trend"].map(st.session_state['settings'].get('trend_colours'))
final_year_list = sorted(list(copydata['trend period'].unique()))
copydata = copydata.sort_values(by = ['parameter name'],ascending = True, key=lambda col: col.str.lower()).reset_index(drop=True)
import plotly.express as px
import plotly.graph_objects as go
fig = px.scatter(copydata, x='trend period', y='parameter name', color="confidence of improving trend",
hover_data=["confidence of improving trend"],# text = "confidence of improving trend",
color_discrete_map = st.session_state['settings'].get('trend_colours'),
category_orders={
'parameter name':sorted(list(copydata['parameter name'].unique()),key=str.casefold),
"confidence of improving trend": list(st.session_state['settings'].get('trend_colours').keys())[0:3],
"trend period" : sorted(list(copydata['trend period'].unique()))
},
title = f"{st.session_state['current_site']}",
)
fig.update_traces(marker_size = st.session_state['settings'].get('plot_settings').get('trend_classification_marker_size'),
marker_opacity = st.session_state['settings'].get('plot_settings').get('marker_opacity'),
marker_symbol = st.session_state['settings'].get('plot_settings').get('basic_marker_shape'))
fig.update_layout(yaxis_title='')
fig.update_layout(xaxis_title='Trend period (years)')
fig.update_layout(legend_title_text='')
fig.update_xaxes(type='category')
final_attributes = list(st.session_state['settings'].get('trend_colours').keys())
fig.update_layout(plot_bgcolor=st.session_state['settings'].get('plot_settings').get('bgcolour'))
fig.update_yaxes(showgrid=st.session_state['settings'].get('plot_settings').get('showgrid'),
gridwidth=st.session_state['settings'].get('plot_settings').get('gridwidth'),
gridcolor=st.session_state['settings'].get('plot_settings').get('gridcolor'))
for trace in fig.data:
trace.showlegend = False
traces_to_include = {x+'/increasing':y for x,y in st.session_state['settings'].get('trend_colours').items() if 'improving' in x}
#add traces for legend
for key_j,value_j in traces_to_include.items():
fig.add_trace(go.Scatter(x=[None],y=[None],mode="markers",name=key_j,
marker=dict(size=st.session_state['settings'].get('plot_settings').get('legend_marker_size'),
color=value_j,
symbol=st.session_state['settings'].get('plot_settings').get('basic_marker_shape')),),)
return fig
#"confidence of improving trend": list(st.session_state['settings'].get('trend_colours').keys()),`,
"pages/1_Rivers.py": `import streamlit as st
import json
import pyodide.http
from PIL import Image
from io import BytesIO
import pandas as pd
import datetime
from plotting_functions import grade_time_plot, grade_time_plot_2_sites, scatter_plot, scatter_plot_2_sites, scatter_plot_2variables, time_series_scatter_plot, trend_classification_plot
css = '''
<style>
.stTabs [data-baseweb="tab-list"] button [data-testid="stMarkdownContainer"] p {
font-size:2rem;
}
</style>
'''
st.markdown(css, unsafe_allow_html=True)
############################################
from functions import load_url,clean_text,get_data_links,load_colourblind_checkbox, load_plotting_checkbox, load_datatable_checkbox, load_second_site_checkbox, load_reverse_second_axis_checkbox, load_log_checkbox, load_log_checkbox_trend
############################################
###############################################################################
############################################
def choose_spatial_area():
spatial_area_names = list(list(st.session_state['site_list'].values())[0].keys())
spatial_user_choice = st.radio('How would you like to select your sites? By: ',['All sites'] + spatial_area_names)
return spatial_user_choice
############################################
def choose_sub_spatial_area(spatial_user_choice,sub_spatial_areas):
sub_spatial_user_choice = st.selectbox(f'Please choose a {spatial_user_choice}: ',['Please select one'] + sub_spatial_areas)
return sub_spatial_user_choice
############################################
def choose_site_of_interest(site_list):
site_user_choice = st.selectbox('Please choose a site: ',['Please select one'] + site_list)
return site_user_choice
############################################
def choose_coparison_site(site_list):
site2_user_choice = st.selectbox('Please choose a second site: ',['Please select one'] + [x for x in site_list if x != st.session_state['site_user_choice']])
return site2_user_choice
############################################
def choose_attribute(attribute_list,text = 'Please choose an attribute to plot: '):
attribute_user_choice = st.selectbox(text,['Please select one'] + attribute_list)
return attribute_user_choice
def choose_attribute_2(attribute_list,text = 'If desired, please choose a second attribute to plot: '):
attribute_user_choice = st.selectbox(text,['Please select one'] + attribute_list)
return attribute_user_choice
############################################
def trend_period(period_list):
trend_user_choice = st.selectbox('Please choose a trend period: ',['Please select one'] + [x for x in period_list])
return trend_user_choice
def choose_scatter_plotting_parameter(parameter_list):
parameter_user_choice = st.selectbox('Please choose a parameter: ',['Please select one'] + [x for x in parameter_list])
return parameter_user_choice
############################################
############################################
############################################
############################################
############################################
# main
#load sidebar image
st.sidebar.image(Image.open(BytesIO(st.session_state['sidebar_image'])))
#load colourblind checkbox
load_colourblind_checkbox()
#load plotting checkbox
load_plotting_checkbox()
#load datatable checkbox
load_datatable_checkbox()
#load site list
if st.session_state['current_page'] != 'Rivers':
url = st.session_state['settings'].get('pages').get('Rivers')
sites = await load_url(url,text=True)
st.session_state['site_list'] = json.loads(sites.encode().decode('utf-8-sig'))
#update current page
st.session_state['current_page'] = 'Rivers'
#clear some variabls from session state
clear_session_state_list = ['site2_user_choice','site2_data']
for variable_j in clear_session_state_list:
st.session_state[variable_j] = None
false_session_state_variables = ['second_site','reverse_2nd_axis']
for variable_j in false_session_state_variables:
st.session_state[variable_j] = False
#write intro message
st.write('---')
st.write("**Welcome** to the rivers state results.")
st.write(f"State and trend analyis is current for data up to **{st.session_state['settings'].get('final_date')}**")
st.write('---')
#choose spatial area
spatial_user_choice = choose_spatial_area()
st.write('---')
if spatial_user_choice == 'All sites':
sub_spatial_user_choice = 'N/A'
st.session_state['filtered_sites'] = sorted(list(st.session_state['site_list'].keys()))
else:
sub_regions = sorted(list(set([x.get(spatial_user_choice) for x in st.session_state['site_list'].values()])))
sub_spatial_user_choice = choose_sub_spatial_area(spatial_user_choice,sub_regions)
if sub_spatial_user_choice != 'Please select one':
st.session_state['filtered_sites'] = sorted([x for x in st.session_state['site_list'].keys() if st.session_state['site_list'].get(x).get(spatial_user_choice) == sub_spatial_user_choice])
# choose site of interest
if (st.session_state['filtered_sites'] is not None) and (sub_spatial_user_choice != 'Please select one'):
st.session_state['site_user_choice'] = choose_site_of_interest(st.session_state['filtered_sites'])
st.write('---')
# display state and raw data link
if st.session_state['site_user_choice'] not in [None,'Please select one']:
st.subheader('Data downloads')
state_data_link,raw_data_link, trend_data_link = get_data_links(topic = 'Rivers')
#try to get trend data for this site
try:
trend_data_in_bytes = await load_url(trend_data_link,text=False)
try:
st.session_state['site_trend_data'] = pd.read_csv(BytesIO(trend_data_in_bytes))
except:st.session_state['site_trend_data'] = pd.read_excel(BytesIO(trend_data_in_bytes))
except Exception as e:
st.session_state['site_trend_data'] = None
#try to get raw data for this site
try:
raw_data_in_bytes = await load_url(raw_data_link,text=False)
try:
st.session_state['site_raw_data'] = pd.read_csv(BytesIO(raw_data_in_bytes))
except:st.session_state['site_raw_data'] = pd.read_excel(BytesIO(raw_data_in_bytes))
except Exception as e:
st.session_state['site_raw_data'] = None
col1,col2 = st.columns(2)
with col1:
place_holder_1 = st.empty()
place_holder_trend = st.empty()
place_holder_3 = st.empty()
place_holder_1.write(f"|--Download **STATE** data for [**{st.session_state['site_user_choice']}**]({state_data_link})--|")
if st.session_state['site_trend_data'] is not None:
place_holder_trend.write(f"|--Download **TREND** data for [**{st.session_state['site_user_choice']}**]({trend_data_link})--|")
else:
place_holder_trend.write(f"|--NO TREND DATA FOUND FOR SITE {st.session_state['site_user_choice']}--|")
place_holder_3.write(f"|--Download **RAW** data for [**{st.session_state['site_user_choice']}**]({raw_data_link})--|")
st.write('---')
#load site data
if st.session_state['current_site'] != st.session_state['site_user_choice']:
url = state_data_link
site_data_in_bytes = await load_url(url,text=False)
try:st.session_state['current_site_data'] = pd.read_csv(BytesIO(site_data_in_bytes))
except:st.session_state['current_site_data'] = pd.read_excel(BytesIO(site_data_in_bytes))
st.session_state['current_site'] = st.session_state['site_user_choice']
st.markdown("""
<style>
.stPlotlyChart {
height: 90vh !important;
}
</style>
""", unsafe_allow_html=True)
if (st.session_state['plot_mode']) or (st.session_state['data_table_mode']):
tab1, tab2 = st.tabs([" **State figures**", " **Trend figures**"])
with tab1:
#THIS TAB DISPLAYS STATE RESULTS
#plot grade_time_plot
if (st.session_state['current_site'] == st.session_state['site_user_choice']) & (st.session_state['current_site_data'] is not None) & (st.session_state['plot_mode']):
col_0,col_1 = st.columns(2)
col_0.write('**NOF grades over time**')
with col_1:
load_second_site_checkbox()
if st.session_state['second_site']:
with col_1:
st.session_state['site2_user_choice'] = choose_coparison_site(st.session_state['filtered_sites'])
if st.session_state['site2_user_choice'] != 'Please select one':
state2_data_link,raw2_data_link,trend_2_data_link = get_data_links(topic = 'Rivers', site2 = True)
url = state2_data_link
site2_data_in_bytes = await load_url(url,text=False)
try:st.session_state['site2_data'] = pd.read_csv(BytesIO(site2_data_in_bytes))
except:st.session_state['site2_data'] = pd.read_excel(BytesIO(site2_data_in_bytes))
with col_1:
place_holder_4 = st.empty()
place_holder_trend_site2 = st.empty()
place_holder_6 = st.empty()
if (st.session_state['site2_data'] is not None) and (st.session_state['site2_user_choice'] != 'Please select one'):
place_holder_4.write(f'''
|--Download **STATE** data for [**{st.session_state['site2_user_choice']}**]({state2_data_link})--|
''')
place_holder_trend_site2.write(f'''
|--Download **TREND** data for [**{st.session_state['site2_user_choice']}**]({trend_2_data_link})--|
''')
place_holder_6.write(f'''
|--Download **RAW** data for [**{st.session_state['site2_user_choice']}**]({raw2_data_link})--|
''')
with col_1:
load_reverse_second_axis_checkbox()
st.plotly_chart(grade_time_plot_2_sites(st.session_state['current_site_data'],
st.session_state['site2_data'],
topic='Rivers'),
use_container_width = True)
if (st.session_state['site2_data'] is not None) and (st.session_state['site2_user_choice'] != 'Please select one'):
st.write('**NOF Grade scatterplot**')
user_attribute = choose_attribute(sorted(list(st.session_state['current_site_data']['attribute type'].unique())),text = f'Please choose an attribute to plot at {st.session_state["site_user_choice"]}: ' )
user_attribute_site_2 = choose_attribute(sorted(list(st.session_state['site2_data']['attribute type'].unique())),text = f'Please choose an attribute to plot at {st.session_state["site2_user_choice"]}: ' )
if (user_attribute not in [None,"Please select one"]) and (user_attribute_site_2 in [None,"Please select one"]):
load_log_checkbox()
st.plotly_chart(scatter_plot(st.session_state['current_site_data'].loc[st.session_state['current_site_data']['attribute type'] == user_attribute].reset_index(drop=True),
user_attribute, data_column = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute),topic='Rivers', sitename = st.session_state['site_user_choice']),
use_container_width = True)
if (user_attribute in [None,"Please select one"]) and (user_attribute_site_2 not in [None,"Please select one"]):
load_log_checkbox()
st.plotly_chart(scatter_plot(st.session_state['site2_data'].loc[st.session_state['site2_data']['attribute type'] == user_attribute_site_2].reset_index(drop=True),
user_attribute_site_2, data_column = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute_site_2),topic='Rivers', sitename = st.session_state['site2_user_choice'], markersymbol = 'triangle-down'),
use_container_width = True)
if (user_attribute not in [None,"Please select one"]) and (user_attribute_site_2 not in [None,"Please select one"]):
load_log_checkbox()
st.plotly_chart(scatter_plot_2_sites(st.session_state['current_site_data'].loc[st.session_state['current_site_data']['attribute type'] == user_attribute].reset_index(drop=True),st.session_state['site2_data'].loc[st.session_state['site2_data']['attribute type'] == user_attribute_site_2].reset_index(drop=True),
user_attribute, user_attribute_site_2,
data_column0 = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute), data_column1 = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute_site_2),topic='Rivers',
sitename0 = st.session_state['site_user_choice'], sitename1 = st.session_state['site2_user_choice']),
use_container_width = True)
else:
c0,c1,c2 = st.columns([1,8,1])
c1.plotly_chart(grade_time_plot(st.session_state['current_site_data'],topic='Rivers'),
use_container_width = True)
c0.write('---')
c1.write('---')
c2.write('---')
with c1:
st.write('**NOF Grade scatterplot**')
user_attribute = choose_attribute(sorted(list(st.session_state['current_site_data']['attribute type'].unique())))
user_attribute_2 = choose_attribute_2(sorted(list([x for x in st.session_state['current_site_data']['attribute type'].unique() if x != user_attribute])))
if (user_attribute not in [None,"Please select one"]) & (user_attribute_2 in [None,"Please select one"]):
load_log_checkbox()
st.plotly_chart(scatter_plot(st.session_state['current_site_data'].loc[st.session_state['current_site_data']['attribute type'] == user_attribute].reset_index(drop=True),
user_attribute, data_column = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute),topic='Rivers', sitename = st.session_state['site_user_choice']),
use_container_width = True)
if (user_attribute not in [None,"Please select one"]) & (user_attribute_2 not in [None,"Please select one"]):
load_log_checkbox()
st.plotly_chart(scatter_plot_2variables(st.session_state['current_site_data'].loc[st.session_state['current_site_data']['attribute type'].isin([user_attribute,user_attribute_2])].reset_index(drop=True),
user_attribute,user_attribute_2,
data_column1 = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute),
data_column2 = st.session_state['settings'].get('nof_attribute_statistics').get(user_attribute_2),
topic='Rivers', sitename = st.session_state['site_user_choice']),
use_container_width = True)
st.write('---')
# show data
if (st.session_state['current_site'] == st.session_state['site_user_choice']) & (st.session_state['current_site_data'] is not None) & (st.session_state['data_table_mode']):
st.write('---')
st.subheader(f'Data table: {st.session_state["current_site"]}')