-
Notifications
You must be signed in to change notification settings - Fork 0
/
FIDS.py
1455 lines (1368 loc) · 53.8 KB
/
FIDS.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
# -*- coding: utf-8 -*-
""" FIDS
Dashboard to interactively visualize and slice FITS datafiles
Quickly sketch and explore data tables and relations sae in FITS format
Line-length: 84 (since thats VSCode on 1080 vertical)
@author: RCCG
"""
# General
import numpy as np
import pandas as pd
import json
from pprint import pprint
from datetime import datetime as dt
from memory_profiler import profile
# IO
from io_tools import get_valid_filelist, get_dict_of_files, get_data_counts, get_brick_data_types
from io_tools import parse_datatype, map_types
from io_tools import load_json
from os.path import isfile
# Processing
from data_tools import get_column_names, reduced_axis_list, args_to_criteria, update_interval
# Data
from data_tools import get_all_data, get_sample_data, get_subsetdata
from data_tools import get_limits, reduce_cols, slice_data, get_relevant_bricks
from data_tools import get_axis_data, format_two_columns, adjust_axis_type
# Polygon
from data_tools import get_data_in_polygon, get_data_in_selection
# Sliders
from setup_dataset import prepare_brick_info
from slider_magic import get_marks, get_range_slider, get_log_range_slider
# Download
from download import generate_df, generate_tmp, generate_small_file, unpack_vars
# Div
from div_updating import hide_unhide_div, update_status
# Dash
import dash
from dash.dependencies import Input, Output, State
import dash_auth
import plotly.graph_objs as go
# Components
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
# Web (Flask, etc.)
from flask import request, session, Response, send_file
import urllib
from urllib.parse import urlencode
# Load Settings
settings = json.load(open('settings.json'))
debug = settings['debug']
if debug:
print("---- Running in Debug-Mode ----")
host = '127.0.0.1'
port = '5001'
enable_login = False
else:
host = settings['host']
port = settings['port']
enable_login = settings['enable_login']
# File names
# TODO: Allow dictionary for renaming in display
filename_list = get_valid_filelist(settings['folderpath'], settings['filetypes'])
# Load Data
# TODO: Allow dictionary for renaming in display
# TODO: Allow other data types
# TODO: Allow heterogeneous data
data = get_dict_of_files(filename_list, settings['folderpath'])
# Get File Descriptions
data_counts = get_data_counts(data, ftype=settings['filetypes'][0])
# Defining columns
# TODO: Read or allow import of UNITS. Maybe visual initialization as an app?
column_names_file = sorted(settings['columns_to_use'])
column_names_data = sorted(data[filename_list[0]].columns.names)
column_names = get_column_names(data, filename_list, column_names_file, column_names_data)
# Reduce Columns to Useful
selected_columns = column_names
selected_columns.remove(settings['name_column']) #[name for name in column_names if name.split('_')[-1] not in ['p50', 'p84', 'p16', 'Exp']]
# Draw Params
display_count_max = settings['display_count_max']
display_count = settings['display_count_default']
display_count_step = settings['display_count_granularity']
####################################################################################
# Columns: Use, Slice, etc.
####################################################################################
# Slider Columns = Selected Columns with proper dtype
brick_data_types = map_types(get_brick_data_types(data, filename_list))
allowed_types = settings["allowed_slider_dtypes"]
slice_col_list = sorted([
col_name for col_name in column_names
if brick_data_types[col_name] in allowed_types
][:settings["max_slider_count"]])
# Get Brick Details
brick_column_details = load_json('brick_column_details.json', savepath=settings['savepath'])
# Fill in missing data if necessary
brick_column_details = prepare_brick_info(
data, brick_column_details, filename_list, slice_col_list,
settings['savepath'], acceptable_types=settings['allowed_slider_dtypes']
)
# Cut out bricks with computed details
filename_list = [
filename for filename in filename_list
if filename in brick_column_details.keys()
]
column_details = {
col_name: {
'min': parse_datatype(np.min([brick_column_details[brick_name][col_name]['min'] for brick_name in filename_list])),
'max': parse_datatype(np.max([brick_column_details[brick_name][col_name]['max'] for brick_name in filename_list])),
}
for col_name in slice_col_list
}
slice_col_list = [col for col in slice_col_list if col in column_details.keys()]
print("Reduced Slice Col List: ", slice_col_list)
# Set up range sliders
slider_style = {
'padding': '0px 20px 3px 20px', # above right below left
'width': 'inherit'
}
# List of: DIV( DIV( title ), DIV( slider ) )
# TODO: Fix Log Sliders
# TODO: Automatically recognize who needs log scale
slice_list = [
html.Div(
get_range_slider(
column_name,
id_given='{}'.format(column_name),
col_range=[
column_details[column_name]['min'],
column_details[column_name]['max']
],
marks=None,
granularity=settings['selection_granularity'],
certainty=settings["slider_number_certainty"]
),
id='{}_div'.format(column_name),
style={
**slider_style,
'display': 'none'
}
)
for column_name in slice_col_list
]
slice_inputs = [
Input('{}'.format(col_name), 'value')
for col_name in slice_col_list
]
slice_states = [
State('{}'.format(col_name), 'value')
for col_name in slice_col_list
]
####################################################################################
# Show only one file if only one present
fileselector_kwargs = {}
if len(filename_list) == 1:
fileselector_kwargs = {
'value': filename_list[0],
'disabled': True
}
debug_elements = []
if debug:
debug_elements.append(
html.Div(
id='debug-container',
children=[
# Status
html.Div(
id='debug-status',
children='debug status'
),
# Shutdown Button
html.Button(
'shutdown app',
id='shutdown-button',
className='button-primary',
type='button-primary'
),
],
style={'padding': '3px'}
)
)
# style
debug_elements = [
html.Div(
debug_elements,
style={
'border': 'solid 1px #A2B1C6',
'border-radius': '5px',
'padding': '5px',
'margin-top': '20px',
}
)]
####################################################################################
# DASH Application
####################################################################################
external_stylesheets = [dbc.themes.BOOTSTRAP, 'assets/FIDS.css']
# TODO: Move to external file
external_userbase = [
['hello', 'world']
]
dropdown_style = {
'padding': '3px'
}
def add_explanation(obj, title=""):
""" Wrap a DCC object with an explanation on mouse-over """
# Inherit "title" from child
if not title:
try:
title = obj.placeholder
except:
title = "??"
# Inherit "style" from child
try:
base_style = obj.style
except:
base_style = {}
return html.Abbr(obj, title=title, style={**base_style, 'border': 'none', 'text-decoration': 'none'})
def Dropdown(*args, **kwargs):
""" Wrap all Dropdowns with an explanation """
return add_explanation(dcc.Dropdown(*args, **kwargs))
def create_formatter(axis_naming, axis_title, column_list):
""" Return collapsable formatting div """
# TODO: Move to table from float/inline-block
return html.Details(
id='{}-formatting'.format(axis_naming),
children=[
# 1: Summary
html.Summary(
'{} Formatting'.format(axis_title),
style={
'font-size': '14px',
'color': '#444',
'padding': '0px 0px 0px 5px'
}
),
# 2: Wrapper for Axis Adjustments
html.Div(
[
# 2.1: Linear vs. Log vs. Exp
html.Div(
Dropdown(
placeholder='Axis scaling',
id='{}-type'.format(axis_naming),
options=[
{'label': i, 'value': i}
for i in ['Linear', 'Log Scale', 'Ln()', 'Log10()', 'e^()', '10^()']
],
value='Linear'
),
style={
'width': '49%',
'display': 'inline-block'
}
),
# 2.2: Increasing vs. Decreasing
html.Div(
Dropdown(
placeholder='Axis orientation',
id='{}-orientation'.format(axis_naming),
options=[
{'label': i, 'value': i}
for i in ['increasing', 'decreasing']
],
value='increasing',
),
style={
'float': 'right',
'width': '49%',
'display': 'inline-block',
}
),
# 2.3: Combined plotting
# Alternatively, pop in after selecting first column on axis?
html.Div(
[
# 2.3.1: Operator
html.Div(
Dropdown(
placeholder='Operator',
id='{}-operator'.format(axis_naming),
options=[
{'label': i, 'value': i}
for i in ['+', '-', '/', 'x']
],
value=''
),
style={
'width': '70px',
'display': 'table-cell',
'vertical-align': 'top'
}
),
# 2.3.2: 2nd Column
html.Div(
Dropdown(
placeholder='Column',
id='{}-combined-column'.format(axis_naming),
options=[
{'label': i, 'value': i}
for i in column_list
],
value=''
),
style={
'display': 'table-cell',
'width': 'auto',
'vertical-align': 'top',
'padding': '0px 0px 0px 5px'
}
)
],
style={
'display': 'table',
'width': '100%'
}
)
],
style={
'padding': '0px 0px 0px 15px',
}
)
],
style={
'display': 'none'
}
)
app = dash.Dash(settings['name'], external_stylesheets=external_stylesheets)
# Use Local Script and CSS
app.scripts.config.serve_locally = True
app.css.config.serve_locally = True
# Allow Login User:Password
if not settings['debug']:
auth = dash_auth.BasicAuth(
app,
external_userbase
)
app.title = 'FITS Dashboard: {}'.format(settings['name'])
# Visual layout
# TODO: Move "style" into CSS
# TODO: Move to CSS Grid from mix of Float and Table
app.layout = html.Div([
html.Div([
# Element 1: Data File Selector
html.Div(
Dropdown(
id='brick_selector',
placeholder='Select FITS files...',
options=[
{'label': '{}'.format(i), 'value': i}
for i in filename_list
],
multi=True,
**fileselector_kwargs
),
style=dropdown_style
),
# Element 2: Data Amount Selector
# TODO: Display sample size somewhere
html.Div(
dcc.Slider(
id='display_count_selection',
min=0,
max=display_count_max,
value=display_count,
step=display_count_step,
marks={
0: '0',
display_count_max: "{:,}".format(display_count_max)
}
),
style={**slider_style, 'height': '34px'}
#html.Div(id="selection-container")
),
# Element 3: New Subsample Generator
# TODO
# Element 4: Axes selections, orientation, type
# Axis Selection
html.Div(
[
# 4.1: Select X-Axis
html.Div(
[
# 4.1.1: X-Axis Column
Dropdown(
id='xaxis_column',
placeholder='Select X-Axis...',
options=[
{'label': i, 'value': i}
for i in selected_columns
],
value=settings['default_x_column']
),
# 4.1.2 X-Axis Formatting
# TODO: Align heights between float (Y), and block (X)
create_formatter('xaxis', 'X-Axis', selected_columns),
],
style={
'width': '49.5%',
'display': 'inline-block'
}
),
# TODO: Allow switching X <-> Y
# 4.2: Select Y-Axis
html.Div(
[
# 4.2.1 Y-Axis Column
Dropdown(
id='yaxis_column',
placeholder='Select Y-Axis...',
options=[
{'label': i, 'value': i}
for i in selected_columns
],
value=settings['default_y_column']
),
# 4.2.2 Y-Axis Formatting
create_formatter('yaxis', 'Y-Axis', selected_columns),
],
style={
'width': '49.5%',
'float': 'right',
'display': 'inline-block'
}
),
# 4.3: Select Z-Axis ?
# TODO: 3D Graphing
],
style=dropdown_style
),
# Element 5: Color coding
html.Div(
[
# 5.1 Color Column
Dropdown(
id='caxis_column',
placeholder='Select Color-Axis...',
options=[
{'label': i, 'value': i}
for i in selected_columns
],
value=settings['default_color_column']
),
# 5.2 Color-Axis Formatting
create_formatter('caxis', 'Color-Axis', selected_columns),
],
style=dropdown_style
),
# Element 6: Size coding
html.Div(
[
Dropdown(
id='saxis_column',
placeholder='Select Size-Axis...',
options=[
{'label': i, 'value': i}
for i in selected_columns
],
),
# TODO: Scaling sizes
],
style=dropdown_style
),
# Element 7: Add column slice sliders
html.Div(
[
Dropdown(
id='column_slicer',
placeholder='Select fields to slice on...',
options=[
{'label': '{}'.format(col_name), 'value': col_name}
for col_name in slice_col_list
],
multi=True
)
],
style=dropdown_style
),
# Element 7.1: Sliders
*slice_list,
# Graph 1: Scatter Plot
html.Div(
dcc.Loading(
dcc.Graph(
id='indicator-graphic',
config={
#'responsive':True, # Whether layout size changes with window size
#'showLink':True, # Link bottom right to plotly chartstudio
#'sendData':True, # Send Data to plotly chartstudio
#'editable':True, # Allow editing of title, axis name, etc.
'modeBarButtonsToRemove': ['watermark', 'displaylogo'],
'displaylogo': False, # Display plotly logo?
'showTips': True,
'toImageButtonOptions':{
'format': 'svg',
'filename': 'image_FIDS'
}
},
style={
'responsive': 'true',
'height': 'inherit',
'width': 'inherit'
}
),
style={
#'border': 'solid 1px #A2B1C6',
#'border-radius': '0px',
'padding': '3px',
'width': 'inherit',
'height': 'inherit',
#'resize': 'vertical',
#'overflow': 'auto'
#'margin-top': '20px'
}
),
style={
'width': 'inherit',
'height': 'inherit'
}
),
# TODO: Graph Styling Section
# Set min/max point size
# Set colorscale
# Element 8: Download Section
html.Details([
# 8.1 Collapsable Header
html.Summary(
'Download Data',
style={'padding': '0px 0px 0px 5px'}
),
# 8.2 Download Section
html.Div(
[
# 8.2.1: Download Raw File
html.Div(
[
# 8.2.3.1 Description
html.Div(
'Download entire file:',
style={
'padding': '3px 20px 0px 3px',
'font-size': '16px',
'font-weight': 'bold'
}
),
# 8.2.3.2 Status
html.Div(
id='download_file_status',
style={
'padding': '0px 0px 0px 3px',
'font-style': 'italic'
}
),
# 8.2.3.3 File download
html.Div(
[
# 8.2.3.3.1 Select File
html.Div(
Dropdown(
id='download_file',
placeholder='Select file to download...',
options=[
{'label': '{}'.format(i), 'value': i}
for i in filename_list
],
multi=False,
),
style={
**dropdown_style,
'display': 'table-cell',
'width': 'auto',
}
),
# 8.2.3.3.2 Download Button
html.A(
html.Button(
'Download *ENTIRE FILE*',
className='button-primary',
type='button-primary',
id='entire-file-button',
n_clicks=0
),
id='download-full-link',
download="rawdata.fits",
href="",
target="_blank",
style={
'padding': '3px',
'display': 'table-cell',
'width': '50px'
}
),
],
style={
'width': '100%',
'display': 'table'
}
)
],
style={
'margin-top': '5px'
}
),
# 8.2.2: Download Selected Criteria
html.Div(
[
# 8.2.2.1 Description
html.Div(
add_explanation(
'Download all data fitting the criteria:',
title="Download all data points that fall within the criteria of sliders, selection, columns graphed and columns selected additionally"
),
style={
'padding': '3px 20px 0px 3px',
'font-size': '16px',
'font-weight': 'bold'
}
),
# 8.2.2.2 Status Bar
html.Div(
id='download_column_status',
style={
'padding': '0px 0px 0px 3px',
'font-style': 'italic'
}
),
# 8.2.2.3 Selection
html.Div([
# 8.2.2.3.1 Column Selector
html.Div(
Dropdown(
id='download_columns',
placeholder='Select fields to download...',
options=[
{'label': '{}'.format(col_name), 'value': col_name}
for col_name in column_names
],
multi=True,
),
style={
**dropdown_style,
'display': 'table-cell',
'width': 'auto'
}
),
# 8.2.2.3.2 Download all data in criteria
# Download
add_explanation(
#html.A(
html.Div(
html.Button(
'Download *BY CRITERIA*',
id='criteria_download_button',
className='button-primary',
type='button-primary',
n_clicks=0
),
# id='download-criteria-link',
# href="",
# target="_blank",
style={
'padding': '3px',
'display': 'table-cell',
'width': '70px'
}
),
title="Download all data points that fall within the criteria of sliders, selection, columns graphed and columns selected additionally"
),
dbc.Modal(
[
dbc.ModalHeader("Confirm Download"),
dbc.ModalBody(
"Confirm below to download",
id='download-modal-body'
),
dbc.ModalFooter(
[
html.A(
dbc.Button(
"Download",
id="download-modal-button",
className="button-primary"
),
id='download-criteria-link',
href="",
target="_blank"
),
dbc.Button(
"Close",
id="download-modal-close",
className="button"
)
]
),
],
id="download-modal",
),
],
style={
'display': 'table',
'width': '100%'
}),
],
style={
#'padding': '0px 5px 0px 0px',
'margin-top': '5px'
}
)
],
style={
'border': 'solid 1px #A2B1C6',
'border-radius': '5px',
'padding': '5px',
#'width': '100%'
}
),
]),
# Element 9: Debug Tools
*debug_elements,
],
style = {
'border': 'solid 1px #A2B1C6',
'border-radius': '5px',
'padding': '5px',
#'margin-top': '20px',
'flex': '1 0 auto'
}),
# Element 11: Footer with links
html.Div(
html.H6(
[
# 11.1 Link to FIDS
html.A(
'FIDS: Flexible Imaging and Display System, ',
id='repository_link',
href='https://www.github.com/the-rccg/FIDS',
target='_blank',
style={
'color': '#444',#rgb(116, 101, 130)',
'text-decoration': 'none',
'letter-spacing': '0.03em'
}
),
# 11.2 Link to University
html.A(
'provided by Ruprecht-Karls Universitaet Heidelberg',
id='university_link',
href='https://www.uni-heidelberg.de/',
target='_blank',
style={
'color': '#444',#'rgb(116, 101, 130)',
'text-decoration': 'none',
'letter-spacing': '0.03em'
}
)
],
style={
'font-size': '14px',
'padding': '5px'
}
),
className='footer',
style={'flex-shrink': '0'}
),
#html.Footer('test',style={'flex-shrink': '0'})
], style={'padding': '5px'})
####################################################################################
# Debug Elements
####################################################################################
if debug:
@app.callback(
Output('debug-status', 'children'),
[Input('shutdown-button', 'n_clicks')]
)
def shutdown(action):
""" shut down flask server via werkzeug """
if action:
if action > 1:
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
ret_str = "shutting down...." #'/dash/shutdown'
else:
ret_str = "please confirm"
else:
ret_str = "debug status"
return ret_str
####################################################################################
# Get Selection
####################################################################################
@app.callback(
Output("download-modal", "is_open"),
[
Input("criteria_download_button", "n_clicks"),
Input("download-modal-close", "n_clicks"),
Input("download-criteria-link", "href")
],
[
State("download-modal", "is_open")
],
)
def toggle_modal(n1, n2, n3, is_open):
if n3:
if (n1 or n2):
return not is_open
return is_open
else:
return False
@app.callback(
[
Output('download-criteria-link', 'href'),
Output('download_column_status', 'children'),
Output('download-modal-body', 'children')
],
[
Input('criteria_download_button', 'n_clicks')
],
[
State('indicator-graphic', 'selectedData'),
State('xaxis_column', 'value'),
State('yaxis_column', 'value'),
State('caxis_column', 'value'),
State('saxis_column', 'value'),
State('xaxis-type', 'value'),
State('yaxis-type', 'value'),
State('xaxis-combined-column', 'value'),
State('yaxis-combined-column', 'value'),
State('caxis-combined-column', 'value'),
State('xaxis-operator', 'value'),
State('yaxis-operator', 'value'),
State('xaxis-combined-column', 'value'),
State('yaxis-combined-column', 'value'),
State('brick_selector', 'value'),
State('download_columns', 'value'),
*slice_states
]
)
def params_to_link(n_clicks, selected_data,
xaxis_name, yaxis_name, caxis_name, saxis_name,
xaxis_type, yaxis_type, #caxis_type, saxis_type,
xaxis_two_name, yaxis_two_name, caxis_two_name,
xaxis_operator, yaxis_operator,
xaxis_second_name, yaxis_second_name,
bricks_selected, download_columns,
*args):
""" Update status and link for downloading by encoding all criteria into the URL. """
# Check: No click
if (not n_clicks):
return [None, None, None]
# Setup: Pre-pack variables
parameters = locals()
# Setup: Remove unnecessary variables
del parameters['selected_data'] # Too big as it incldues every single point displayed
del parameters['args'] # Relevant re-added with proper names for encoding
# Setup: Status
status = [html.Div('Status: ')]
status = update_status(status, bricks_selected, "Bricks Selected")
# Check: No Brick
if (not bricks_selected):
status[0] = html.Div('Status: Failed.')
return [None, status, status]
# Setup: Axes to include
axis_name_list = reduced_axis_list(
download_columns, xaxis_name, yaxis_name, caxis_name, saxis_name,
xaxis_two_name, yaxis_two_name, caxis_two_name
)
parameters['axis_name_list'] = axis_name_list
status = update_status(status, axis_name_list, "Columns to Download Selected")
# Check: No axis
if len(axis_name_list) == 0:
status[0] = html.Div('Status: Failed.')
return [None, status, status]
# Otherwise Go Ahead-->
status[0] = html.Div('Status: Please confirm by clicking "Download" below!')
t0 = dt.now()
# Setup: Include Slider Criteria
criteria_dict = args_to_criteria(bricks_selected, slice_col_list, brick_column_details, args)
status = update_status(status, criteria_dict, "Criteria Specified", formats=["-","-"])
# Check for combined axis
is_xaxis_combined = (xaxis_two_name) and (xaxis_operator)
is_yaxis_combined = (yaxis_two_name) and (yaxis_operator)
# Selection Adjustments
vertices = []
if selected_data:
# Option 1: Rectangle
if ('range' in selected_data.keys()):
# Step 1.1: Update Criteria
x_interval = selected_data['range']['x']
y_interval = selected_data['range']['y']
if (xaxis_name in criteria_dict.keys()) and (not is_xaxis_combined):
criteria_dict[xaxis_name] = update_interval(
criteria_dict, xaxis_name,
np.min(x_interval), np.max(x_interval)
)
if (yaxis_name in criteria_dict.keys() )and (not is_yaxis_combined):
criteria_dict[yaxis_name] = update_interval(
criteria_dict, yaxis_name,
np.min(y_interval), np.max(y_interval)
)
status = update_status(status, [x_interval, y_interval], "Rectangle Selected", formats=["-","-"])
# Option 2: Curve
if 'lassoPoints' in selected_data.keys():
# Step 2.1: Create array of vertices
vertices = np.array(list(zip(selected_data['lassoPoints']['x'], selected_data['lassoPoints']['y'])))
# Step 2.2: Update Criteria
xmin, ymin = vertices.min(0)
xmax, ymax = vertices.max(0)
if (xaxis_name in criteria_dict.keys()) and (not is_xaxis_combined):
criteria_dict[xaxis_name] = update_interval(
criteria_dict, xaxis_name,
xmin, xmax
)
if (yaxis_name in criteria_dict.keys()) and (not is_yaxis_combined):
criteria_dict[yaxis_name] = update_interval(
criteria_dict, yaxis_name,
ymin, ymax
)
status = update_status(status, vertices.shape[0], "Lasso Vertices Selected", formats=["-","-"])
# Pack criteria
parameters['vertices'] = vertices
parameters['criteria_dict'] = criteria_dict
# Require confirmation
if not(n_clicks % 2) and (n_clicks!=1):
return ["", status, status]
else:
return [
'/dash/selected_download.csv?'+urlencode(parameters),
status,
status
]
@app.server.route('/dash/selected_download.csv')
def download_selection():
"""Serve download of defined data.
TODO:
- Fix the delay between updating URL and clicking the download link
"""
# Unpack arguments - TODO: use proper decoding
# Repack to types and nested types
variables = unpack_vars(request.args.to_dict()) #urllib.parse.parse_qs(str(request.query_string))
# 1. Get relevant data based on slice criteria
return_data = get_all_data(
variables['bricks_selected'],
variables['axis_name_list'],
variables['criteria_dict'],
brick_column_details,