-
Notifications
You must be signed in to change notification settings - Fork 21
/
core.py
2273 lines (2129 loc) · 120 KB
/
core.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
'''
Pivot chart maker core functionality and csv, gdx applications
'''
from __future__ import division
import os
import sys
import traceback
import shutil
import re
import math
import json
import numpy as np
import pandas as pd
import collections
import bokeh as bk
import bokeh.io as bio
import bokeh.layouts as bl
import bokeh.models as bm
import bokeh.models.widgets as bmw
import bokeh.models.sources as bms
import bokeh.models.tools as bmt
import bokeh.models.callbacks as bmc
import bokeh.plotting as bp
import bokeh.palettes as bpa
import bokeh.resources as br
import bokeh.embed as be
import datetime
import six.moves.urllib.parse as urlp
import subprocess as sp
import jinja2 as ji
import reeds_bokeh as rb
import logging
import requests
from defaults import (DEFAULT_DATA_TYPE, DATA_TYPE_OPTIONS)
#Setup logger
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(message)s')
if not logger.hasHandlers():
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)
logger.addHandler(sh)
#Defaults to configure:
DEFAULT_CUSTOM_SORTS = {} #Keys are column names and values are lists of values in the desired sort order
DEFAULT_CUSTOM_COLORS = {} #Keys are column names and values are dicts that map column values to colors (hex strings)
DATA_TYPE_OPTIONS = DATA_TYPE_OPTIONS + ['CSV']
WIDTH = 300
HEIGHT = 300
PLOT_FONT_SIZE = 10
PLOT_AXIS_LABEL_SIZE = 8
PLOT_LABEL_ORIENTATION = 45
OPACITY = 0.8
X_SCALE = 1
Y_SCALE = 1
CIRCLE_SIZE = 9
BAR_WIDTH = 0.8
LINE_WIDTH = 2
#colors taken from bpa.all_palettes['Category20'][20] and rearranged so that pairs are split
COLORS = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
'#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5', '#c49c94', '#f7b6d2', '#c7c7c7', '#dbdb8d', '#9edae5']*1000
#here are the colors from bpa.all_palettes['Category20c'][20] and rearranged so that quads are split
COLORS_QUAD = ['#3182bd','#e6550d','#31a354','#756bb1','#636363',
'#6baed6','#fd8d3c','#74c476','#9e9ac8','#969696',
'#9ecae1','#fdae6b','#a1d99b','#bcbddc','#bdbdbd',
'#c6dbef','#fdd0a2','#c7e9c0','#dadaeb','#d9d9d9']*1000
HIST_NUM_BINS = 20
MAP_PALETTE = 'Blues' #See https://bokeh.pydata.org/en/latest/docs/reference/palettes.html for options
C_NORM = "#31AADE"
CHARTTYPES = ['Dot', 'Line', 'Dot-Line', 'Bar', 'Area', 'Area Map', 'Line Map']
STACKEDTYPES = ['Bar', 'Area']
AGGREGATIONS = ['None', 'sum(a)', 'ave(a)', 'sum(a)/sum(b)', 'sum(a*b)/sum(b)', '[sum(a*b)/sum(b)]/[sum(a*c)/sum(c)]']
ADV_BASES = ['Consecutive', 'Total']
MAP_FONT_SIZE = 10
MAP_NUM_BINS = 9
MAP_WIDTH = 500
MAP_OPACITY = 1
MAP_BOUNDARY_WIDTH = 0.1
MAP_LINE_WIDTH = 2
RANGE_OPACITY_MULT = 0.3
RANGE_GLYPH_MAP = {'Line': 'Area', 'Dot': 'Bar', 'Dot-Line': 'Area'}
#List of widgets that use columns as their selectors
WDG_COL = ['x', 'y', 'x_group', 'series', 'explode', 'explode_group']
#List of widgets that don't use columns as selector and share general widget update function
WDG_NON_COL = ['chart_type', 'range', 'y_agg', 'adv_op', 'explode_grid', 'adv_col_base',
'adv_op2', 'adv_col_base2', 'adv_op3', 'adv_col_base3', 'plot_title', 'plot_title_size',
'sort_data', 'width', 'height', 'opacity', 'sync_axes', 'x_min', 'x_max', 'x_scale',
'x_title', 'series_limit', 'x_title_size', 'x_major_label_size', 'x_major_label_orientation',
'y_min', 'y_max', 'y_scale', 'y_title', 'y_title_size', 'y_major_label_size', 'hist_num_bins', 'hist_weight',
'circle_size', 'bar_width', 'cum_sort', 'line_width', 'range_show_glyphs', 'net_levels', 'bokeh_tools',
'map_bin', 'map_num', 'map_nozeros', 'map_min', 'map_max', 'map_manual',
'map_arrows','map_arrow_size','map_arrow_loc','map_width', 'map_font_size', 'map_boundary_width',
'map_line_width', 'map_opacity', 'map_palette', 'map_palette_2', 'map_palette_break']
#initialize globals dict for variables that are modified within update functions.
#custom_sorts (dict): Keys are column names and values are lists of values in the desired sort order
#custom_colors (dict): Keys are column names and values are dicts that map column values to colors (hex strings)
GL = {'df_source':None, 'df_plots':None, 'columns':None, 'data_source_wdg':None, 'variant_wdg':{},
'widgets':None, 'wdg_defaults': collections.OrderedDict(), 'controls': None, 'plots':None, 'custom_sorts': DEFAULT_CUSTOM_SORTS,
'custom_colors': DEFAULT_CUSTOM_COLORS}
#os globals
this_dir_path = os.path.dirname(os.path.realpath(__file__))
out_path = this_dir_path + '/out'
def initialize():
'''
On initial load, read 'widgets' parameter from URL query string and use to set data source (data_source)
and widget configuration object (wdg_config). Initialize controls and plots areas of layout, and
send data to opened browser.
'''
logger.info('***Initializing...')
wdg_config = {}
args = bio.curdoc().session_context.request.arguments
wdg_arr = args.get('widgets')
data_source = ''
data_type = DEFAULT_DATA_TYPE
reset_wdg_defaults()
if wdg_arr is not None:
wdg_config = json.loads(urlp.unquote(wdg_arr[0].decode('utf-8')))
if 'data' in wdg_config:
data_source = str(wdg_config['data'])
if 'data_type' in wdg_config:
data_type = str(wdg_config['data_type'])
#build widgets and plots
GL['data_source_wdg'] = build_data_source_wdg(data_type, data_source)
GL['controls'] = bl.column(list(GL['data_source_wdg'].values()), css_classes=['widgets_section'])
GL['plots'] = bl.column([], css_classes=['plots_section'])
layout = bl.row(GL['controls'], GL['plots'], css_classes=['full_layout'])
if data_source != '':
update_data_source(init_load=True, init_config=wdg_config)
set_wdg_col_options()
update_plots()
bio.curdoc().add_root(layout)
bio.curdoc().title = "Exploding Pivot Chart Maker"
logger.info('***Done Initializing')
def reset_wdg_defaults():
'''
Set global GL['wdg_defaults']
'''
GL['wdg_defaults'] = collections.OrderedDict()
GL['wdg_defaults']['data'] = ''
GL['wdg_defaults']['data_type'] = DEFAULT_DATA_TYPE
def static_report(data_type, data_source, static_presets, report_path, report_format, html_num, output_dir, auto_open, variant_wdg_config=[]):
'''
Build static HTML and excel/csv reports based on specified presets.
Args:
data_type (string): Type of data.
data_source (string): Path to data for which a report will be made
static_presets (list of dicts): List of presets for which to make report. Each preset has these keys:
'name' (required): name of preset
'config' (required): a dict of widget configurations, where keys are keys of GL['widgets'] and values are values of those widgets. See preset_wdg()
'sheet_name' (optional): If specified, this is used for the excel sheet name for this preset. Must be unique.
'download_full_source' (optional): If specified, this allows us to download the full data source, without creating a figure/view.
report_path (string): The path to the report file.
report_format (string): string that contains 'html', 'excel', 'csv', or a combination of these, specifying which reports to make.
html_num (string): 'multiple' if we are building separate html reports for each section, and 'one' for one html report with all sections.
output_dir (string): the directory into which the resulting reports will be saved.
auto_open (string): either "Yes" to automatically open report files, or "No"
variant_wdg_config (list of dicts): After data source is set, this allows us to set any other variant_wdg values.
Returns:
Nothing: HTML and Excel files are created
'''
#build initial widgets and plots globals
GL['data_source_wdg'] = build_data_source_wdg()
GL['controls'] = bl.column(list(GL['data_source_wdg'].values()))
GL['plots'] = bl.column([])
#Update data source widget with input value
GL['data_source_wdg']['data_type'].value = data_type
GL['data_source_wdg']['data'].value = data_source
#update any variant_wdg
for vwc in variant_wdg_config:
if vwc['type'] == 'active':
GL['widgets'][vwc['name']].active = vwc['val']
elif vwc['type'] == 'value':
GL['widgets'][vwc['name']].value = vwc['val']
time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
if os.path.exists(output_dir):
os.rename(output_dir, output_dir + '-archive-'+time)
output_dir = output_dir + '/'
os.makedirs(output_dir)
fh = logging.FileHandler(output_dir + 'report.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
#copy report file to output_dir
if report_path != '':
shutil.copy2(report_path, output_dir)
#copy csv data_source to output_dir if not a CSV data type.
if data_type != 'CSV' and data_source.endswith('.csv'):
shutil.copy2(data_source, output_dir)
data_sources = data_source.split('|')
if 'csv' in report_format:
os.makedirs(output_dir + 'csvs')
if 'excel' in report_format:
excel_report_path = output_dir + 'report.xlsx'
excel_report = pd.ExcelWriter(excel_report_path)
excel_meta = []
excel_meta.append('Build date/time: ' + time)
excel_meta.append('Data Source(s):')
for ds in data_sources:
excel_meta.append(ds)
excel_meta.append('Default Config:')
for vwc in variant_wdg_config:
excel_meta.append(vwc['name'] + ': ' + str(vwc['val']))
pd.Series(excel_meta).to_excel(excel_report, 'meta', index=False, header=False)
if 'html' in report_format:
with open(this_dir_path + '/templates/static/index.html', 'r') as template_file:
template_string=template_file.read()
template = ji.Template(template_string)
resources = br.Resources()
header = '<h3>Build date/time:</h3><p>' + time + '</p>'
header += '<h3>Data Source(s):</h3><ul>'
for ds in data_sources:
header += '<li>' + ds + '</li>'
header += '</ul>'
header += '<h3>Default Config:</h3><ul>'
for vwc in variant_wdg_config:
header += '<li>' + vwc['name'] + ': ' + str(vwc['val']) + '</li>'
header += '</ul>'
if html_num == 'one':
header += '<h3>Section Links:</h3><ol>'
sec_i = 1
for static_preset in static_presets:
sheet_name = ' [sheet="' + static_preset['sheet_name'] + '"]' if 'sheet_name' in static_preset else ''
header += '<li><a href="#section-' + str(sec_i) + '">' + static_preset['name'] + sheet_name + '</a></li>'
sec_i += 1
header += '</ol>'
header_row = bl.row(bmw.Div(text=header, css_classes=['header_section']))
if html_num == 'one':
static_plots = []
static_plots.append(header_row)
elif html_num == 'multiple':
contents_str = '<h3>Contents:</h3><ul>'
#for each preset, set the widgets in preset_wdg(). Gather plots into separate sections of the html report,
#and gather data into separate sheets of excel report
sec_i = 1
vizit_data = []
for static_preset in static_presets:
name = static_preset['name']
try:
logger.info('***Building report section: ' + name + '...')
preset = static_preset['config']
download_full_source = False
if 'download_full_source' in static_preset and static_preset['download_full_source'] is True:
download_full_source = True
preset_wdg(preset, download_full_source)
if 'html' in report_format and download_full_source is False:
title = bmw.Div(text='<h2 id="section-' + str(sec_i) + '">' + str(sec_i) + '. ' + name + '</h2>')
legend = bmw.Div(text=GL['widgets']['legend'].text)
display_config = bmw.Div(text=GL['widgets']['display_config'].text)
title_row = bl.row(title)
content_row = bl.row(GL['plots'].children + [legend] + [display_config])
if html_num == 'one':
static_plots.append(title_row)
static_plots.append(content_row)
elif html_num == 'multiple':
html = be.file_html([title_row, content_row], resources=resources, template=template)
html_file_name = str(sec_i) + '_' + name
html_file_name = re.sub(r'[\\/:"*?<>|]', '-', html_file_name) #replace disallowed file name characters with dash
html_path = output_dir + html_file_name + '.html'
with open(html_path, 'w') as f:
f.write(html)
contents_str += '<li><a href="' + html_file_name + '.html">' + str(sec_i) + '. ' + name + '</a></li>'
if 'html' in report_format:
#Vizit-related outputs (allowing download_full_source as well)
vizit_data.append({
'sec_i': sec_i,
'data': GL['df_source'] if download_full_source else GL['df_plots'],
'preset': static_preset
})
if 'excel' in report_format:
sheet_name = static_preset['sheet_name'] if 'sheet_name' in static_preset else str(sec_i) + '_' + name
sheet_name = re.sub(r"[\\/*\[\]:?]", '-', sheet_name) #replace disallowed sheet name characters with dash
sheet_name = sheet_name[:31] #excel sheet names can only be 31 characters long
if download_full_source:
GL['df_source'].to_excel(excel_report, sheet_name, index=False)
else:
GL['df_plots'].to_excel(excel_report, sheet_name, index=False)
if 'csv' in report_format:
sheet_name = static_preset['sheet_name'] if 'sheet_name' in static_preset else str(sec_i) + '_' + name
sheet_name = re.sub(r'[\\/:"*?<>|]', '-', sheet_name) #replace disallowed sheet name characters with dash
if download_full_source:
GL['df_source'].to_csv(output_dir + 'csvs/' + sheet_name + '.csv', index=False)
else:
GL['df_plots'].to_csv(output_dir + 'csvs/' + sheet_name + '.csv', index=False)
except Exception:
logger.info('***Error in section ' + str(sec_i) + '...\n' + traceback.format_exc())
if html_num == 'one':
static_plots.append(bl.row(bmw.Div(text='<h2 id="section-' + str(sec_i) + '" class="error">' + str(sec_i) + '. ' + name + '. ERROR!</h2>')))
sec_i += 1
if 'excel' in report_format:
excel_report.close()
if 'html' in report_format:
if html_num == 'one':
html = be.file_html(static_plots, resources=resources, template=template)
html_path = output_dir + 'report.html'
with open(html_path, 'w') as f:
f.write(html)
if auto_open == 'Yes':
sp.Popen(os.path.abspath(html_path), shell=True)
elif html_num == 'multiple':
contents_str += '</ul>'
html = '<!DOCTYPE html><html><body>' + header + contents_str + '</body></html>'
html_path = output_dir + 'contents.html'
with open(html_path, 'w') as f:
f.write(html)
if auto_open == 'Yes':
sp.Popen(os.path.abspath(html_path), shell=True)
vizit_report(data_type, data_source, vizit_data, output_dir, auto_open)
logger.info('***Done building report')
def vizit_report(data_type, data_source, vizit_data, output_dir, auto_open):
vizit_config = {'fileNames': [], 'globalStyleFile': 'vizit_styles.csv', 'dashboards':[]}
#map bokehpivot to vizit
widget_map = {
'explode': 'explode',
'x': 'x',
'y': 'y',
'series': 'name',
}
style_map = {
'width': 'Plot Width (px)',
'height': 'Plot Height (px)',
# 'x_major_label_size': 'X Tick Font Size (pt)',
}
chart_type_map = {
'Dot': 'dot',
'Line': 'line',
'Dot-Line': 'line dot',
'Bar': 'bar',
'Area': 'bar',
'Area Map': 'custom region map',
'Line Map': 'lat/lon/width line map',
}
data_dict = {}
for v in vizit_data:
if v['data'].empty:
continue
v = v.copy() #So I don't edit the input itself
#Remove Net Level column if it exists
if v['data'].columns[-1].startswith('Net Level'):
v['data'].drop(v['data'].columns[-1], axis=1, inplace=True)
sheet_name = v['preset']['sheet_name'] if 'sheet_name' in v['preset'] else str(v['sec_i']) + '_' + v['preset']['name']
sheet_name = re.sub(r'[\\/:"*?<>|]', '-', sheet_name) #replace disallowed sheet name characters with dash
vizit_config['fileNames'].append(f'{sheet_name}.csv')
if 'download_full_source' not in v['preset']:
if 'chart_type' not in v['preset']['config']:
v['preset']['config']['chart_type'] = 'Dot'
trace_config = {
'dataSource': f'{sheet_name}.csv',
'type': chart_type_map[v['preset']['config']['chart_type']],
'agg': 'sum',
}
style_config = {}
for w in widget_map:
if w in v['preset']['config']:
trace_config[widget_map[w]] = v['preset']['config'][w]
for s in style_map:
if s in v['preset']['config']:
style_config[style_map[s]] = v['preset']['config'][s]
#vizit doesn't support 'explode_group', so make a new concatenated column and set 'explode' to that
if 'explode_group' in v['preset']['config'] and v['preset']['config']['explode_group'] != 'None':
new_col = v['preset']['config']['explode'] + ' - ' + v['preset']['config']['explode_group']
cur_cols = v['data'].columns.tolist()
v['data'][new_col] = (
v['data'][v['preset']['config']['explode']].astype(str) + ' - ' +
v['data'][v['preset']['config']['explode_group']].astype(str)
)
#Put new_col at the beginning
v['data'] = v['data'][[new_col] + cur_cols].copy()
trace_config['explode'] = new_col
if v['preset']['config']['chart_type'] == 'Area Map':
reg = v['preset']['config']['x']
if reg == 'rb':
geojson = 'https://raw.githubusercontent.com/mmowers/vizitfiles/main/US_PCA.json'
featureidkey = 'properties.rb'
elif reg == 'st':
geojson = 'https://raw.githubusercontent.com/mmowers/vizitfiles/main/us-states.json'
featureidkey = 'properties.code'
#Replace 'y' key with 'z', and replace 'x' with 'locations'
trace_config['z'] = trace_config.pop('y')
trace_config['locations'] = trace_config.pop('x')
trace_config['geojson'] = geojson
trace_config['geojsonboundaries'] = geojson
trace_config['featureidkey'] = featureidkey
style_config['Map Zoom'] = '6'
style_config['Map Center Latitude'] = '40'
style_config['Map Center Longitude'] = '-96'
style_config['Colorscale (region)'] = 'Reds'
if 'sync_axes' not in v['preset']['config'] or v['preset']['config']['sync_axes'] == 'Yes':
if v['preset']['config']['chart_type'] == 'Area Map':
style_config['Colorscale Min (region)'] = v['data'][trace_config['z']].min()
style_config['Colorscale Max (region)'] = v['data'][trace_config['z']].max()
else:
val_col = trace_config['y']
if v['preset']['config']['chart_type'] in STACKEDTYPES and 'series' in v['preset']['config']:
#sum across series for y_min and y_max
ser_col = v['preset']['config']['series']
df_pos = v['data'][v['data'][val_col] > 0].copy()
df_neg = v['data'][v['data'][val_col] < 0].copy()
df_pos = df_pos.drop(columns=ser_col)
df_neg = df_neg.drop(columns=ser_col)
groupby_cols = [c for c in df_pos.columns if c != val_col]
df_pos = df_pos.groupby(groupby_cols, as_index=False)[val_col].sum()
df_neg = df_neg.groupby(groupby_cols, as_index=False)[val_col].sum()
y_min = df_neg[val_col].min() if df_neg[val_col].min() < 0 else 0
y_max = df_pos[val_col].max() if df_pos[val_col].max() > 0 else 0
else:
y_min = v['data'][val_col].min() if v['data'][val_col].min() < 0 else 0
y_max = v['data'][val_col].max() if v['data'][val_col].max() > 0 else 0
style_config['Y Min'] = y_min
style_config['Y Max'] = y_max
dashboard = {'title': v['preset']['name'], 'charts':[{'traces':[trace_config], 'style':style_config}]}
vizit_config['dashboards'].append(dashboard)
#Add the data itself (even if we're downloading the full source, so we can make charts with the full data)
data_dict[f'{sheet_name}.csv'] = v['data'].to_dict(orient='list')
bpStyleDir = f'{this_dir_path}/in/reeds2'
ls_df = []
#Read in styles from bokehpivot
for f in os.listdir(bpStyleDir):
if f.endswith('_style.csv'):
df = pd.read_csv(os.path.join(bpStyleDir,f))
df['column_name'] = f.replace('_style.csv','')
df = df.rename(columns={'order':'column_value'})
ls_df.append(df)
df_style = pd.concat(ls_df, ignore_index=True)
df_style = df_style[['column_name','column_value','color']].copy()
#Add styles from scenarios.csv if applicable
if data_type != 'CSV' and data_source.endswith('.csv'):
df_scen = pd.read_csv(data_source)
df_scen['column_name'] = 'scenario'
df_scen = df_scen.rename(columns={'name':'column_value'})
df_scen = df_scen[['column_name','column_value','color']].copy()
df_style = pd.concat([df_style, df_scen],sort=False,ignore_index=True)
data_dict['vizit_styles.csv'] = df_style.to_dict(orient='list')
vizit_config['fileNames'].append('vizit_styles.csv')
vizit_commit = '7011d363e40386264bedb3155629729b225fd22e'
vizit_url = f'https://raw.githubusercontent.com/mmowers/vizit/{vizit_commit}/index.html'
f_out_str = requests.get(vizit_url).text
data_str = json.dumps(data_dict, separators=(',',':'))
config_str = json.dumps(vizit_config, separators=(',',':'))
f_out_str = re.sub('let config_load = .*;\n', f'let config_load = {config_str};\n', f_out_str, 1)
f_out_str = re.sub('let rawData = .*;\n', f'let rawData = {data_str};\n', f_out_str, 1)
with open(f'{output_dir}report_vizit.html', 'w') as f_out:
f_out.write(f_out_str)
if auto_open == 'Yes':
sp.Popen(os.path.abspath(f'{output_dir}report_vizit.html'), shell=True)
def preset_wdg(preset, download_full_source=False):
'''
Reset widgets and then set them to that specified in input preset
Args:
preset (dict): keys are widget names, and values are the desired widget values. Filters are entered as a list of labels under the 'filter' key.
Returns:
Nothing: widget values are set.
'''
#First set all wdg_variant values, if they exist, in order that they appear in wdg_variant, an ordered dict.
variant_presets = [key for key in list(GL['variant_wdg'].keys()) if key in preset]
for key in variant_presets:
if isinstance(GL['widgets'][key], bmw.groups.AbstractGroup):
GL['widgets'][key].active = [GL['widgets'][key].labels.index(i) for i in preset[key]]
elif isinstance(GL['widgets'][key], bmw.inputs.InputWidget):
GL['widgets'][key].value = preset[key]
if download_full_source:
return
#these variables are set after the variant_wdg presets because otherwise they diverge from the globals
wdg = GL['widgets']
wdg_variant = GL['variant_wdg']
wdg_defaults = GL['wdg_defaults']
#Now set x to none to prevent chart rerender
wdg['x'].value = 'None'
#gather widgets to reset
wdg_resets = [i for i in wdg_defaults if i not in list(wdg_variant.keys())+['x', 'data', 'data_type', 'render_plots', 'auto_update']]
#reset widgets if they are not default
for key in wdg_resets:
if isinstance(wdg[key], bmw.groups.AbstractGroup) and wdg[key].active != wdg_defaults[key]:
wdg[key].active = wdg_defaults[key]
elif isinstance(wdg[key], bmw.inputs.InputWidget) and wdg[key].value != wdg_defaults[key]:
wdg[key].value = wdg_defaults[key]
#set all presets except x and filter, in order that they appear in wdg, an ordered dict.
#Filters are handled separately, after that. x will be set at end, triggering render of chart.
common_presets = [key for key in list(wdg.keys()) if key in preset and key not in list(wdg_variant.keys())+['x', 'filter']]
for key in common_presets:
if isinstance(wdg[key], bmw.groups.AbstractGroup):
wdg[key].active = [wdg[key].labels.index(i) for i in preset[key]]
elif isinstance(wdg[key], bmw.inputs.InputWidget):
wdg[key].value = preset[key]
#filters are handled separately. We must deal with the active arrays of each filter
if 'filter' in preset:
for fil in preset['filter']:
preset_filter = preset['filter'][fil]
#find index of associated filter:
for j, col in enumerate(GL['columns']['filterable']):
if col == fil:
#get filter widget associated with found index
wdg_fil = wdg['filter_'+str(j)]
#build the new_active list, starting with zeros
#for each label given in the preset, set corresponding active to 1
if isinstance(preset_filter, str):
if preset_filter == 'last':
new_active = [len(wdg_fil.labels) - 1]
elif isinstance(preset_filter, dict):
new_active = list(range(len(wdg_fil.labels)))
if 'start' in preset_filter:
start = wdg_fil.labels.index(str(preset_filter['start']))
if 'end' in preset_filter:
end = wdg_fil.labels.index(str(preset_filter['end']))
else:
end = len(wdg_fil.labels) - 1
new_active = list(range(start,end+1))
if 'exclude' in preset_filter:
new_active = [n for n in new_active if wdg_fil.labels[n] not in preset_filter['exclude']]
else: #we are using a list of labels
new_active = []
for lab in preset_filter:
if str(lab) in wdg_fil.labels:
index = wdg_fil.labels.index(str(lab))
new_active.append(index)
wdg_fil.active = new_active
break
#finally, set x, which will trigger the data and chart updates.
wdg['x'].value = preset['x']
def build_data_source_wdg(data_type=DEFAULT_DATA_TYPE, data_source=''):
'''
Return the initial data source widget, prefilled with an input data_source
Args:
data_type (string):
data_source (string): Path to data source
Returns:
wdg (ordered dict): ordered dictionary of bokeh.models.widgets (in this case only one) for data source.
'''
wdg = collections.OrderedDict()
wdg['readme'] = bmw.Div(text='<a href="https://github.nrel.gov/ReEDS/bokehpivot" target="_blank">README</a>')
wdg['data_dropdown'] = bmw.Div(text='Data Source (required)', css_classes=['data-dropdown'])
wdg['data_type'] = bmw.Select(title='Type', value=data_type, options=DATA_TYPE_OPTIONS, css_classes=['wdgkey-data-type', 'data-drop'])
wdg['data'] = bmw.TextInput(title='Path', value=data_source, css_classes=['wdgkey-data', 'data-drop'])
wdg['data_type'].on_change('value', update_data_type)
wdg['data'].on_change('value', update_data)
return wdg
def get_df_csv(data_source):
'''
Read csv(s) into a pandas dataframe, and determine which columns of the dataframe
are discrete (strings), continuous (numbers), able to be filtered (aka filterable),
and able to be used as a series (aka seriesable). NA values are filled based on the type of column,
and the dataframe and columns are returned.
Args:
data_source (string): Path to csv file or directory containing csv files with the same column structure
Returns:
df_source (pandas dataframe): A dataframe of the source, with filled NA values.
cols (dict): Keys are categories of columns of df_source, and values are a list of columns of that category.
'''
logger.info('***Fetching csv(s)...')
dfs = []
sources = data_source.split('|')
for src in sources:
src = src.strip()
if os.path.isdir(src):
#if this is a directory, get all csv within it, assuming they are structured the same way, and add a column for filename
for file in os.listdir(src):
if file.endswith(".csv"):
filepath = os.path.join(src,file)
df = pd.read_csv(filepath, low_memory=False)
filename = os.path.splitext(file)[0]
df['filename'] = filename
dfs.append(df)
else:
#This is a csv file, or pd.read_csv will show error if it isn't
df = pd.read_csv(src, low_memory=False)
if len(sources) > 1:
filename = os.path.splitext(os.path.basename(src))[0]
df['filename'] = filename
dfs.append(df)
df_source = pd.concat(dfs,sort=False,ignore_index=True)
cols = {}
cols['all'] = df_source.columns.values.tolist()
cols['discrete'] = [x for x in cols['all'] if df_source[x].dtype == object]
cols['continuous'] = [x for x in cols['all'] if x not in cols['discrete']]
cols['x-axis'] = cols['all']
cols['y-axis'] = cols['continuous']
cols['filterable'] = cols['discrete']+[x for x in cols['continuous'] if len(df_source[x].unique()) < 500 and df_source[x].dtype != float]
cols['seriesable'] = cols['filterable']
df_source[cols['discrete']] = df_source[cols['discrete']].fillna('{BLANK}')
df_source[cols['continuous']] = df_source[cols['continuous']].fillna(0)
logger.info('***Done fetching csv(s).')
return (df_source, cols)
def get_wdg_csv():
'''
Create report widgets for csv file.
Returns:
topwdg (ordered dict): Dictionary of bokeh.model.widgets.
'''
topwdg = collections.OrderedDict()
topwdg['report_dropdown'] = bmw.Div(text='Build Report', css_classes=['report-dropdown'])
topwdg['report_custom'] = bmw.TextInput(title='Enter path to report file', value='', css_classes=['report-drop'], visible=False)
topwdg['report_format'] = bmw.TextInput(title='Enter type(s) of report (html,excel,csv)', value='html,excel', css_classes=['report-drop'], visible=False)
topwdg['report_debug'] = bmw.Select(title='Debug Mode', value='No', options=['Yes','No'], css_classes=['report-drop'], visible=False)
topwdg['report_build'] = bmw.Button(label='Build Report', button_type='success', css_classes=['report-drop'], visible=False)
topwdg['report_build_separate'] = bmw.Button(label='Build Separate Reports', button_type='success', css_classes=['report-drop'], visible=False)
topwdg['report_build'].on_click(build_report)
topwdg['report_build_separate'].on_click(build_report_separate)
return topwdg
def build_report(html_num='one'):
'''
Build the chosen report.
Args:
html_num (string): 'multiple' if we are building separate html reports for each section, and 'one' for one html report with all sections.
'''
data_type = '"CSV"'
report_path = GL['widgets']['report_custom'].value
report_path = report_path.replace('"', '')
report_path = '"' + report_path + '"'
report_format = '"' + GL['widgets']['report_format'].value + '"'
time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
output_dir = '"' + out_path + '/report-' + time + '"'
data_source = '"' + GL['widgets']['data'].value.replace('"', '') + '"'
if html_num == 'one':
auto_open = '"Yes"'
else:
auto_open = '"No"'
start_str = 'start python'
if GL['widgets']['report_debug'].value == 'Yes':
start_str = 'start cmd /K python -m pdb '
sp.call(start_str + ' "' + this_dir_path + '/reports/interface_report.py" ' + data_type + ' ' + data_source + ' ' + report_path + ' ' + report_format + ' "' + html_num + '" ' + output_dir + ' ' + auto_open, shell=True)
def build_report_separate():
'''
Build the report with separate html files for each section of the report.
'''
build_report(html_num='multiple')
def get_wdg_gdx(data_source):
'''
Create a parameter select widget and return it.
Args:
data_source (string): Path to gdx file.
Returns:
topwdg (ordered dict): Dictionary of bokeh.model.widgets.
'''
return #need to implement!
def build_widgets(df_source, cols, init_load=False, init_config={}, wdg_defaults={}):
'''
Use a dataframe and its columns to set widget options. Widget values may
be set by URL parameters via init_config.
Args:
df_source (pandas dataframe): Dataframe of the csv source.
cols (dict): Keys are categories of columns of df_source, and values are a list of columns of that category.
init_load (boolean, optional): If this is the initial page load, then this will be True, else False.
init_config (dict): Initial widget configuration passed via URL.
wdg_defaults (dict): Keys are widget names and values are the default values of the widgets.
Returns:
wdg (ordered dict): Dictionary of bokeh.model.widgets.
'''
#Add widgets
logger.info('***Build main widgets...')
wdg = collections.OrderedDict()
wdg['chart_type_dropdown'] = bmw.Div(text='Chart', css_classes=['chart-dropdown'])
wdg['chart_type'] = bmw.Select(title='Chart Type', value='Dot', options=CHARTTYPES, css_classes=['wdgkey-chart_type', 'chart-drop'], visible=False)
wdg['range'] = bmw.Select(title='Add Ranges (Line and Dot only)', value='No', options=['No', 'Within Series', 'Between Series', 'Boxplot'], css_classes=['wdgkey-range', 'chart-drop'], visible=False)
wdg['x_dropdown'] = bmw.Div(text='X-Axis (required)', css_classes=['x-dropdown'])
wdg['x'] = bmw.Select(title='X-Axis (required)', value='None', options=['None'] + cols['x-axis'] + ['histogram_x'], css_classes=['wdgkey-x', 'x-drop'], visible=False)
wdg['x_group'] = bmw.Select(title='Group X-Axis By', value='None', options=['None'] + cols['seriesable'], css_classes=['wdgkey-x_group', 'x-drop'], visible=False)
wdg['y_dropdown'] = bmw.Div(text='Y-Axis (required)', css_classes=['y-dropdown'])
wdg['y'] = bmw.Select(title='a (required)', value='None', options=['None'] + cols['y-axis'], css_classes=['wdgkey-y', 'y-drop'], visible=False)
wdg['y_b'] = bmw.Select(title='b (optional, no update)', value='None', options=['None'] + cols['y-axis'], css_classes=['wdgkey-y_b', 'y-drop'], visible=False)
wdg['y_c'] = bmw.Select(title='c (optional, no update)', value='None', options=['None'] + cols['y-axis'], css_classes=['wdgkey-y_c', 'y-drop'], visible=False)
wdg['y_agg'] = bmw.Select(title='Y-Axis Aggregation', value='sum(a)', options=AGGREGATIONS, css_classes=['wdgkey-y_agg', 'y-drop'], visible=False)
wdg['series_dropdown'] = bmw.Div(text='Series', css_classes=['series-dropdown'])
wdg['series'] = bmw.Select(title='Separate Series By', value='None', options=['None'] + cols['seriesable'],
css_classes=['wdgkey-series', 'series-drop'], visible=False)
wdg['series_limit'] = bmw.TextInput(title='Number of series to show', value='All', css_classes=['wdgkey-series', 'series-drop'], visible=False)
wdg['explode_dropdown'] = bmw.Div(text='Explode', css_classes=['explode-dropdown'])
wdg['explode'] = bmw.Select(title='Explode By', value='None', options=['None'] + cols['seriesable'], css_classes=['wdgkey-explode', 'explode-drop'], visible=False)
wdg['explode_group'] = bmw.Select(title='Group Exploded Charts By', value='None', options=['None'] + cols['seriesable'],
css_classes=['wdgkey-explode_group', 'explode-drop'], visible=False)
wdg['explode_grid'] = bmw.Select(title='Make Grid Plot', value='No', options=['Yes','No'], css_classes=['wdgkey-explode_grid', 'explode-drop'], visible=False)
wdg['adv_dropdown'] = bmw.Div(text='Operations', css_classes=['adv-dropdown'])
wdg['adv_op'] = bmw.Select(title='First Operation', value='None', options=['None', 'Difference', 'Ratio'], css_classes=['wdgkey-adv_op', 'adv-drop'], visible=False)
wdg['adv_col'] = bmw.Select(title='Operate Across', value='None', options=['None'] + cols['all'], css_classes=['wdgkey-adv_col', 'adv-drop'], visible=False)
wdg['adv_col_base'] = bmw.Select(title='Base', value='None', options=['None'], css_classes=['wdgkey-adv_col_base', 'adv-drop'], visible=False)
wdg['adv_op2'] = bmw.Select(title='Second Operation', value='None', options=['None', 'Difference', 'Ratio'], css_classes=['wdgkey-adv_op', 'adv-drop'], visible=False)
wdg['adv_col2'] = bmw.Select(title='Operate Across', value='None', options=['None'] + cols['all'], css_classes=['wdgkey-adv_col', 'adv-drop'], visible=False)
wdg['adv_col_base2'] = bmw.Select(title='Base', value='None', options=['None'], css_classes=['wdgkey-adv_col_base', 'adv-drop'], visible=False)
wdg['adv_op3'] = bmw.Select(title='Third Operation', value='None', options=['None', 'Difference', 'Ratio'], css_classes=['wdgkey-adv_op', 'adv-drop'], visible=False)
wdg['adv_col3'] = bmw.Select(title='Operate Across', value='None', options=['None'] + cols['all'], css_classes=['wdgkey-adv_col', 'adv-drop'], visible=False)
wdg['adv_col_base3'] = bmw.Select(title='Base', value='None', options=['None'], css_classes=['wdgkey-adv_col_base', 'adv-drop'], visible=False)
wdg['filters'] = bmw.Div(text='Filters', css_classes=['filters-dropdown'])
wdg['filters_update'] = bmw.Button(label='Update Filters', button_type='success', css_classes=['filters-update'], visible=False)
for j, col in enumerate(cols['filterable']):
val_list = [str(i) for i in sorted(df_source[col].unique().tolist())]
wdg['heading_filter_'+str(j)] = bmw.Div(text=col, css_classes=['filter-head'], visible=False)
wdg['filter_sel_all_'+str(j)] = bmw.Button(label='Select All', button_type='success', css_classes=['filter-drop','select-all-none'], visible=False)
wdg['filter_sel_none_'+str(j)] = bmw.Button(label='Select None', button_type='success', css_classes=['filter-drop','select-all-none'], visible=False)
wdg['filter_'+str(j)] = bmw.CheckboxGroup(labels=val_list, active=list(range(len(val_list))), css_classes=['wdgkey-filter_'+str(j), 'filter-drop'], visible=False)
select_all_callback = bmc.CustomJS(args=dict(cb_wdg_fil=wdg['filter_'+str(j)]), code="""
cb_wdg_fil.active = Array.from(Array(cb_wdg_fil.labels.length).keys())
cb_wdg_fil.change.emit();
""")
select_none_callback = bmc.CustomJS(args=dict(cb_wdg_fil=wdg['filter_'+str(j)]), code="""
cb_wdg_fil.active = []
cb_wdg_fil.change.emit();
""")
wdg['filter_sel_all_'+str(j)].js_on_event(bk.events.ButtonClick, select_all_callback)
wdg['filter_sel_none_'+str(j)].js_on_event(bk.events.ButtonClick, select_none_callback)
wdg['adjustments'] = bmw.Div(text='Plot Adjustments', css_classes=['adjust-dropdown'])
wdg['width'] = bmw.TextInput(title='Plot Width (px)', value=str(WIDTH), css_classes=['wdgkey-width', 'adjust-drop'], visible=False)
wdg['height'] = bmw.TextInput(title='Plot Height (px)', value=str(HEIGHT), css_classes=['wdgkey-height', 'adjust-drop'], visible=False)
wdg['plot_title'] = bmw.TextInput(title='Plot Title', value='', css_classes=['wdgkey-plot_title', 'adjust-drop'], visible=False)
wdg['plot_title_size'] = bmw.TextInput(title='Plot Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-plot_title_size', 'adjust-drop'], visible=False)
wdg['opacity'] = bmw.TextInput(title='Opacity (0-1)', value=str(OPACITY), css_classes=['wdgkey-opacity', 'adjust-drop'], visible=False)
wdg['sync_axes'] = bmw.Select(title='Sync Axes', value='Yes', options=['Yes', 'No'], css_classes=['adjust-drop'], visible=False)
wdg['x_scale'] = bmw.TextInput(title='X Scale', value=str(X_SCALE), css_classes=['wdgkey-x_scale', 'adjust-drop'], visible=False)
wdg['x_min'] = bmw.TextInput(title='X Min', value='', css_classes=['wdgkey-x_min', 'adjust-drop'], visible=False)
wdg['x_max'] = bmw.TextInput(title='X Max', value='', css_classes=['wdgkey-x_max', 'adjust-drop'], visible=False)
wdg['x_title'] = bmw.TextInput(title='X Title', value='', css_classes=['wdgkey-x_title', 'adjust-drop'], visible=False)
wdg['x_title_size'] = bmw.TextInput(title='X Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-x_title_size', 'adjust-drop'], visible=False)
wdg['x_major_label_size'] = bmw.TextInput(title='X Labels Font Size', value=str(PLOT_AXIS_LABEL_SIZE), css_classes=['wdgkey-x_major_label_size', 'adjust-drop'], visible=False)
wdg['x_major_label_orientation'] = bmw.TextInput(title='X Labels Degrees', value=str(PLOT_LABEL_ORIENTATION),
css_classes=['wdgkey-x_major_label_orientation', 'adjust-drop'], visible=False)
wdg['y_scale'] = bmw.TextInput(title='Y Scale', value=str(Y_SCALE), css_classes=['wdgkey-y_scale', 'adjust-drop'], visible=False)
wdg['y_min'] = bmw.TextInput(title='Y Min', value='', css_classes=['wdgkey-y_min', 'adjust-drop'], visible=False)
wdg['y_max'] = bmw.TextInput(title='Y Max', value='', css_classes=['wdgkey-y_max', 'adjust-drop'], visible=False)
wdg['y_title'] = bmw.TextInput(title='Y Title', value='', css_classes=['wdgkey-y_title', 'adjust-drop'], visible=False)
wdg['y_title_size'] = bmw.TextInput(title='Y Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-y_title_size', 'adjust-drop'], visible=False)
wdg['y_major_label_size'] = bmw.TextInput(title='Y Labels Font Size', value=str(PLOT_AXIS_LABEL_SIZE), css_classes=['wdgkey-y_major_label_size', 'adjust-drop'], visible=False)
wdg['circle_size'] = bmw.TextInput(title='Circle Size (Dot Only)', value=str(CIRCLE_SIZE), css_classes=['wdgkey-circle_size', 'adjust-drop'], visible=False)
wdg['bar_width'] = bmw.TextInput(title='Bar Width (Bar Only)', value=str(BAR_WIDTH), css_classes=['wdgkey-bar_width', 'adjust-drop'], visible=False)
wdg['bar_width_desc'] = bmw.Div(text='<strong>Flags</strong> <em>w</em>: use csv file for widths, <em>c</em>: convert x axis to quantitative based on widths in csv file', css_classes=['adjust-drop', 'description'], visible=False)
wdg['sort_data'] = bmw.Select(title='Sort Data', value='Yes', options=['Yes', 'No'], css_classes=['wdgkey-sort_data', 'adjust-drop'], visible=False)
wdg['cum_sort'] = bmw.Select(title='Cumulative Sort', value='None', options=['None', 'Ascending', 'Descending'], css_classes=['wdgkey-cum_sort','adjust-drop'], visible=False)
wdg['hist_num_bins'] = bmw.TextInput(title='Histogram # of bins', value=str(HIST_NUM_BINS), css_classes=['wdgkey-hist_num_bins', 'adjust-drop'], visible=False)
wdg['hist_weight'] = bmw.Select(title='Weighted Histogram', value='Yes', options=['Yes', 'No'], css_classes=['wdgkey-hist_weight', 'adjust-drop'], visible=False)
wdg['line_width'] = bmw.TextInput(title='Line Width (Line Only)', value=str(LINE_WIDTH), css_classes=['wdgkey-line_width', 'adjust-drop'], visible=False)
wdg['range_show_glyphs'] = bmw.Select(title='Show Line/Dot (Range Only)', value='Yes', options=['Yes','No'], css_classes=['wdgkey-range_show_glyphs', 'adjust-drop'], visible=False)
wdg['net_levels'] = bmw.Select(title='Add Net Levels to Stacked', value='Yes', options=['Yes','No'], css_classes=['wdgkey-net_levels', 'adjust-drop'], visible=False)
wdg['bokeh_tools'] = bmw.Select(title='Show Bokeh Tools', value='Yes', options=['Yes','No'], css_classes=['wdgkey-bokeh_tools', 'adjust-drop'], visible=False)
wdg['custom_styles'] = bmw.TextInput(title='Custom Styles CSV', value='', css_classes=['wdgkey-custom_styles', 'adjust-drop'], visible=False)
wdg['map_adjustments'] = bmw.Div(text='Map Adjustments', css_classes=['map-dropdown'])
wdg['map_bin'] = bmw.Select(title='Bin Type', value='Auto Equal Num', options=['Auto Equal Num', 'Auto Equal Width', 'Manual'], css_classes=['wdgkey-map_bin', 'map-drop'], visible=False)
wdg['map_num'] = bmw.TextInput(title='# of bins (Auto Only)', value=str(MAP_NUM_BINS), css_classes=['wdgkey-map_num', 'map-drop'], visible=False)
wdg['map_nozeros'] = bmw.Select(title='Ignore Zeros', value='Yes', options=['Yes', 'No'], css_classes=['wdgkey-map_nozeros', 'map-drop'], visible=False)
wdg['map_palette'] = bmw.TextInput(title='Map Palette', value=MAP_PALETTE, css_classes=['wdgkey-map_palette', 'map-drop'], visible=False)
wdg['map_palette_desc'] = bmw.Div(text='See <a href="https://bokeh.pydata.org/en/latest/docs/reference/palettes.html" target="_blank">palette options</a> or all_red, all_blue, all_green, all_gray. Palette must accommodate # of bins', css_classes=['map-drop', 'description'], visible=False)
wdg['map_palette_2'] = bmw.TextInput(title='Map Palette 2 (Optional)', value='', css_classes=['wdgkey-map_palette_2', 'map-drop'], visible=False)
wdg['map_palette_2_desc'] = bmw.Div(text='Bins will be split between palettes.', css_classes=['map-drop', 'description'], visible=False)
wdg['map_palette_break'] = bmw.TextInput(title='Dual Palette Breakpoint (Optional)', value='', css_classes=['wdgkey-map_palette_break', 'map-drop'], visible=False)
wdg['map_palette_break_desc'] = bmw.Div(text='The bin that contains this breakpoint will divide the palettes.', css_classes=['map-drop', 'description'], visible=False)
wdg['map_min'] = bmw.TextInput(title='Minimum (Equal Width Only)', value='', css_classes=['wdgkey-map_min', 'map-drop'], visible=False)
wdg['map_max'] = bmw.TextInput(title='Maximum (Equal Width Only)', value='', css_classes=['wdgkey-map_max', 'map-drop'], visible=False)
wdg['map_manual'] = bmw.TextInput(title='Manual Breakpoints (Manual Only)', value='', css_classes=['wdgkey-map_manual', 'map-drop'], visible=False)
wdg['map_manual_desc'] = bmw.Div(text='Comma separated list of values (e.g. -10,0,0.5,6), with one fewer value than # of bins', css_classes=['map-drop', 'description'], visible=False)
wdg['map_width'] = bmw.TextInput(title='Map Width (px)', value=str(MAP_WIDTH), css_classes=['wdgkey-map_width', 'map-drop'], visible=False)
wdg['map_font_size'] = bmw.TextInput(title='Title Font Size', value=str(MAP_FONT_SIZE), css_classes=['wdgkey-map_font_size', 'map-drop'], visible=False)
wdg['map_boundary_width'] = bmw.TextInput(title='Boundary Line Width', value=str(MAP_BOUNDARY_WIDTH), css_classes=['wdgkey-map_boundary_width', 'map-drop'], visible=False)
wdg['map_line_width'] = bmw.TextInput(title='Line Width', value=str(MAP_LINE_WIDTH), css_classes=['wdgkey-map_line_width', 'map-drop'], visible=False)
wdg['map_opacity'] = bmw.TextInput(title='Opacity (0-1)', value=str(MAP_OPACITY), css_classes=['wdgkey-map_opacity', 'map-drop'], visible=False)
wdg['map_arrows'] = bmw.Select(title='Add Arrows', value='No', options=['Yes','No'], css_classes=['wdgkey-map_arrows', 'map-drop'], visible=False)
wdg['map_arrow_size'] = bmw.TextInput(title='Arrow Size (px)', value='7', css_classes=['wdgkey-map_arrow_size', 'map-drop'], visible=False)
wdg['map_arrow_loc'] = bmw.TextInput(title='Arrow Location (0=start, 1=end)', value='0.8', css_classes=['wdgkey-map_arrow_loc', 'map-drop'], visible=False)
wdg['auto_update_dropdown'] = bmw.Div(text='Auto/Manual Update', css_classes=['update-dropdown'])
wdg['auto_update'] = bmw.Select(title='Auto Update (except filters)', value='Enable', options=['Enable', 'Disable'], css_classes=['update-drop'], visible=False)
wdg['update'] = bmw.Button(label='Manual Update', button_type='success', css_classes=['update-drop'], visible=False)
wdg['render_plots'] = bmw.Select(title='Render Plots', value='Yes', options=['Yes', 'No'], css_classes=['update-drop'], visible=False)
wdg['download_dropdown'] = bmw.Div(text='Download/Export', css_classes=['download-dropdown'])
wdg['download_date'] = bmw.Select(title='Add Date', value='Yes', options=['Yes', 'No'], css_classes=['download-drop'], visible=False)
wdg['download_prefix'] = bmw.TextInput(title='Prefix', value='', css_classes=['download-drop'], visible=False)
wdg['download_all'] = bmw.Button(label='All Files of View', button_type='success', css_classes=['download-drop'], visible=False)
wdg['download_csv'] = bmw.Button(label='CSV of View', button_type='success', css_classes=['download-drop'], visible=False)
wdg['download_html'] = bmw.Button(label='HTML of View', button_type='success', css_classes=['download-drop'], visible=False)
wdg['download_url'] = bmw.Button(label='URL of View', button_type='success', css_classes=['download-drop'], visible=False)
wdg['download_report'] = bmw.Button(label='Python Report of View', button_type='success', css_classes=['download-drop'], visible=False)
wdg['download_preset'] = bmw.Button(label='Preset of View', button_type='success', css_classes=['download-drop'], visible=False)
wdg['download_source'] = bmw.Button(label='CSV of Full Data Source', button_type='success', css_classes=['download-drop'], visible=False)
wdg['legend_dropdown'] = bmw.Div(text='Legend', css_classes=['legend-dropdown'])
wdg['legend'] = bmw.Div(text='', css_classes=['legend-drop'])
wdg['display_config'] = bmw.Div(text='', css_classes=['display-config'])
#save defaults
save_wdg_defaults(wdg, wdg_defaults)
#use init_config (from 'widgets' parameter in URL query string) to configure widgets.
if init_load:
initialize_wdg(wdg, init_config)
#Add update functions for widgets
wdg['filters_update'].on_click(update_plots)
wdg['update'].on_click(update_plots)
wdg['download_all'].on_click(download_all)
wdg['download_csv'].on_click(download_csv)
wdg['download_html'].on_click(download_html)
wdg['download_url'].on_click(download_url)
wdg['download_report'].on_click(download_report)
wdg['download_preset'].on_click(download_preset)
wdg['download_source'].on_click(download_source)
wdg['adv_col'].on_change('value', update_adv_col)
wdg['adv_col2'].on_change('value', update_adv_col2)
wdg['adv_col3'].on_change('value', update_adv_col3)
wdg['custom_styles'].on_change('value', update_custom_styles)
for name in WDG_COL:
wdg[name].on_change('value', update_wdg_col)
for name in WDG_NON_COL:
wdg[name].on_change('value', update_wdg)
logger.info('***Done with main widgets.')
return wdg
def initialize_wdg(wdg, init_config):
'''
Set values of wdg based on init_config
Args:
wdg (ordered dict): Dictionary of bokeh.model.widgets.
init_config (dict): Initial widget configuration passed via URL.
Returns:
Nothing: wdg is modified
'''
for key in init_config:
if key in wdg:
if hasattr(wdg[key], 'value'):
wdg[key].value = str(init_config[key])
elif hasattr(wdg[key], 'active'):
wdg[key].active = init_config[key]
def save_wdg_defaults(wdg, wdg_defaults):
'''
Save wdg_defaults based on wdg
Args:
wdg (ordered dict): Dictionary of bokeh.model.widgets.
wdg_defaults (dict): Keys are widget names and values are the default values of the widgets.
Returns:
Nothing: wdg_defaults is set for applicable keys in wdg
'''
for key in wdg:
if isinstance(wdg[key], bmw.groups.AbstractGroup):
wdg_defaults[key] = wdg[key].active
elif isinstance(wdg[key], bmw.inputs.InputWidget):
wdg_defaults[key] = wdg[key].value
def set_df_plots(df_source, cols, wdg, custom_sorts={}):
'''
Apply filters, scaling, aggregation, and sorting to source dataframe, and return the result.
Args:
df_source (pandas dataframe): Dataframe of the csv source.
cols (dict): Keys are categories of columns of df_source, and values are a list of columns of that category.
wdg (ordered dict): Dictionary of bokeh model widgets.
custom_sorts (dict): Keys are column names. Values are lists of values in the desired sort order.
Returns:
df_plots (pandas dataframe): df_source after having been filtered, scaled, aggregated, and sorted.
'''
logger.info('***Filtering, Scaling, Aggregating, Adv Operations, Sorting...')
startTime = datetime.datetime.now()
df_plots = df_source.copy()
#Apply filters
for j, col in enumerate(cols['filterable']):
active = [wdg['filter_'+str(j)].labels[i] for i in wdg['filter_'+str(j)].active]
if col in cols['continuous']:
active = np.asarray(active)
active = active.astype(df_plots[col].dtype)
active = active.tolist()
df_plots = df_plots[df_plots[col].isin(active)]
if df_plots.empty:
return df_plots
#Limit number of series if indicated
if wdg['series'].value != 'None' and wdg['series_limit'].value.isdigit():
df_top = df_plots[[wdg['series'].value, wdg['y'].value]].copy()
df_top[wdg['y'].value] = df_top[wdg['y'].value].abs()
df_top = df_top.groupby([wdg['series'].value], sort=False, as_index=False).sum()
df_top = df_top.sort_values(by=[wdg['y'].value], ascending=False)
top_series = df_top.head(int(wdg['series_limit'].value))[wdg['series'].value].tolist()
df_plots.loc[~df_plots[wdg['series'].value].isin(top_series), wdg['series'].value] = 'Other'
#Apply Aggregation
if wdg['y'].value in cols['continuous'] and wdg['y_agg'].value != 'None' and wdg['x'].value != 'histogram_x':
groupby_cols = [wdg['x'].value]
if wdg['x_group'].value != 'None':
groupby_cols = [wdg['x_group'].value] + groupby_cols
if wdg['series'].value != 'None':
groupby_cols = [wdg['series'].value] + groupby_cols
if wdg['explode'].value != 'None':
groupby_cols = [wdg['explode'].value] + groupby_cols
if wdg['explode_group'].value != 'None':
groupby_cols = [wdg['explode_group'].value] + groupby_cols
df_grouped = df_plots.groupby(groupby_cols, sort=False)
df_plots = df_grouped.apply(apply_aggregation, wdg['y_agg'].value, wdg['y'].value, wdg['y_b'].value, wdg['y_c'].value, wdg['range'].value).reset_index()
#The index of each group's dataframe is added as another column it seems. So we need to remove it:
df_plots.drop(df_plots.columns[len(groupby_cols)], axis=1, inplace=True)
#Make histogram
if wdg['x'].value == 'histogram_x':
weights = df_plots[wdg['y'].value] if wdg['hist_weight'].value == 'Yes' else None
yhist, binedges = np.histogram(df_plots[wdg['y'].value], bins=int(wdg['hist_num_bins'].value), weights=weights)
groupby_cols = []
if wdg['series'].value != 'None':
groupby_cols = [wdg['series'].value] + groupby_cols
if wdg['explode'].value != 'None':
groupby_cols = [wdg['explode'].value] + groupby_cols
if wdg['explode_group'].value != 'None':
groupby_cols = [wdg['explode_group'].value] + groupby_cols
if groupby_cols == []:
bincenters = np.mean(np.vstack([binedges[0:-1],binedges[1:]]), axis=0)
df_plots = pd.DataFrame({wdg['x'].value: bincenters, wdg['y'].value: yhist})
else:
def group_apply_hist(group, binedges):
weights = group[wdg['y'].value] if wdg['hist_weight'].value == 'Yes' else None
if wdg['sync_axes'].value == 'Yes':
yhist, binedges = np.histogram(group[wdg['y'].value], bins=binedges, weights=weights)
else:
yhist, binedges = np.histogram(group[wdg['y'].value], bins=int(wdg['hist_num_bins'].value), weights=weights)
bincenters = np.mean(np.vstack([binedges[0:-1],binedges[1:]]), axis=0)
return pd.DataFrame({wdg['x'].value: bincenters, wdg['y'].value: yhist})
df_grouped = df_plots.groupby(groupby_cols, sort=False)
df_plots = df_grouped.apply(group_apply_hist, binedges).reset_index()
df_plots.drop(df_plots.columns[len(groupby_cols)], axis=1, inplace=True)
groupby_cols += [wdg['x'].value]
#Check for range chart
range_cols = []
if wdg['range'].value == 'Within Series':
range_cols = ['range_min', 'range_max']
#Do Advanced Operations
df_plots = do_op(df_plots, wdg, cols, '')
df_plots = do_op(df_plots, wdg, cols, '2')
df_plots = do_op(df_plots, wdg, cols, '3')
#For arrow maps, flip the x axis when there are negatives so that all values are positive in the correct direction.
if wdg['chart_type'].value == 'Line Map' and wdg['map_arrows'].value == 'Yes':
df_plots[['temp_from','temp_to']] = df_plots[wdg['x'].value].str.split('-',expand=True)
idx_neg = df_plots[wdg['y'].value] < 0
df_plots.loc[idx_neg, wdg['x'].value] = df_plots.loc[idx_neg, 'temp_to'] + '-' + df_plots.loc[idx_neg, 'temp_from']
df_plots[wdg['y'].value] = df_plots[wdg['y'].value].abs()
df_plots.drop(['temp_from','temp_to'], axis='columns',inplace=True)
#Scale Axes
if wdg['x_scale'].value != '' and wdg['x'].value in cols['continuous'] + ['histogram_x']:
df_plots[wdg['x'].value] = df_plots[wdg['x'].value] * float(wdg['x_scale'].value)
if wdg['y_scale'].value != '' and wdg['y'].value in cols['continuous']:
df_plots[wdg['y'].value] = df_plots[wdg['y'].value] * float(wdg['y_scale'].value)
#For cum_sort set to "Ascending" or "Descending" we will sort by cumulative y value.
#If net levels are shown, we must also calculate cumulative y value.
cum_sort_cond = wdg['cum_sort'].value != 'None'
net_level_cond = wdg['net_levels'].value == 'Yes' and wdg['chart_type'].value in STACKEDTYPES
net_level_col = []
if cum_sort_cond or net_level_cond:
#adjust groupby_cols from Aggregation section above, and remove series from group if it is there
net_group_cols = [c for c in groupby_cols if c != wdg['series'].value]
#group and sum across series to get the cumulative y for each x
df_net_group = df_plots.groupby(net_group_cols, sort=False)
df_net = df_net_group[wdg['y'].value].sum().reset_index()
if cum_sort_cond:
df_cum = df_net.rename(columns={wdg['y'].value: 'y_cumulative'})
if wdg['cum_sort'].value == 'Descending':
#multiply by -1 so that we sort from large to small instead of small to large
df_cum['y_cumulative'] = df_cum['y_cumulative']*-1
df_plots = df_plots.merge(df_cum, how='left', on=net_group_cols, sort=False)
if net_level_cond:
net_level_col_name = 'Net Level ' + wdg['y'].value
net_level_col = [net_level_col_name]
df_net_lev = df_net.rename(columns={wdg['y'].value: net_level_col_name})
df_plots = df_plots.merge(df_net_lev, how='left', on=net_group_cols, sort=False)
#Sort Dataframe
sortby_cols = []
if wdg['sort_data'].value == 'Yes':
sortby_cols = [wdg['x'].value]
if wdg['x_group'].value != 'None':