-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdashboard.py
3375 lines (2694 loc) · 134 KB
/
dashboard.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
"""
Web-based Dashboard for the Python Package DBMS Benchmarker
Copyright (C) 2020 Jascha Jestel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import dash
#import dash_core_components as dcc
from dash import dcc
#import dash_html_components as html
from dash import html
#import dash_table
from dash import dash_table
from dash.dependencies import Input, Output, State, MATCH, ALL
from dash.exceptions import PreventUpdate
from dash import no_update
import plotly.figure_factory as ff
import plotly.graph_objects as go
import pandas as pd
import layout
from dbmsbenchmarker import *
from flask_caching import Cache
import argparse
import json
import time
import copy
import urllib.parse
import re
import logging
import base64
import dash_auth
#logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.ERROR)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Dashboard for interactive inspection of dbmsbenchmarker results.')
parser.add_argument('-r', '--result-folder',
help='Folder storing benchmark result files.',
default='./') # set your own default path here
parser.add_argument('-a', '--anonymize',
help='Anonymize all dbms.',
action='store_true',
default=False)
parser.add_argument('-u', '--user',
help='User name for auth protected access.',
default=None)
parser.add_argument('-p', '--password',
help='Password for auth protected access.',
default=None)
parser.add_argument('-d', '--debug',
help='Show debug information.',
action='store_true',
default=False)
args = parser.parse_args()
result_path = args.result_folder
# verify that result path was given
if result_path is None:
raise ValueError('No result path was given.')
# create inspector instance using the result path
evaluate = inspector.inspector(result_path, anonymize=args.anonymize)
# preview of all available experiments in result path
preview = evaluate.get_experiments_preview()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
# Dash's basic stylesheet
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# Create Dash App instance
app = dash.Dash(__name__, external_stylesheets=external_stylesheets, suppress_callback_exceptions=True)
# Create Dash App Auth instance
if args.user is not None and args.password is not None:
VALID_USERNAME_PASSWORD_PAIRS = { # Keep this out of source code repository - save in a file or a database
args.user: args.password
}
auth = dash_auth.BasicAuth(
app,
VALID_USERNAME_PASSWORD_PAIRS
)
# Assign layout to app
app.layout = layout.serve_layout(preview)
# TODO activate caching
# cache = Cache(app.server, config={
# # Note that filesystem cache doesn't work on systems with ephemeral
# # filesystems like Heroku.
# 'CACHE_TYPE': 'filesystem',
# 'CACHE_DIR': 'cache-directory',
#
# # should be equal to maximum number of users on the app at a single time
# # higher numbers will store more data in the filesystem
# 'CACHE_THRESHOLD': 10
# })
# TODO activate caching by replacing load_experiment function
# @cache.memoize(50)
# def load_experiment(code: str, session_id: str) -> inspector.inspector:
# """
# :return: evaluate object with the desired experiment loaded
# """
# e = inspector.inspector(result_path)
# e.load_experiment(code)
# return e
def load_experiment(code: str) -> inspector.inspector:
"""
Loads the experiment with given code for global evaluate object.
This doesn't work well with multiple users exploring different experiments,
because experiments will reload constantly.
The advantage of changing the global evaluate variable is the memoization of at least one experiment.
If the evaluate object works independently, use above load_experiment function.
:return: evaluate object with the desired experiment loaded
"""
try:
if evaluate.get_experiment_workload_properties()['code'] != code:
evaluate.load_experiment(code)
except:
evaluate.load_experiment(code)
return evaluate
def get_connections_by_filter(filter_by: str, e: inspector.inspector) -> dict:
"""
Call evaluate.get_experiment_list_connections_by_... method depending on a given filter keyword.
If the filter keyword is not supported a KeyError is raised.
:param filter_by: filter keyword to filter connections by
:param e: evaluate object
:return: dict like: {'cl-worker4': ['connection1', ‘connection2', ...], ...} containing ALL connections.
"""
if filter_by == 'DBMS':
connections_by_filter = e.get_experiment_list_connections_by_dbms()
elif filter_by == 'Node':
connections_by_filter = e.get_experiment_list_connections_by_node()
elif filter_by == 'Script':
connections_by_filter = e.get_experiment_list_connections_by_script()
elif filter_by == 'GPU':
connections_by_filter = e.get_experiment_list_connections_by_hostsystem('GPU')
elif filter_by == 'Client':
connections_by_filter = e.get_experiment_list_connections_by_parameter('client')
#connections_by_filter = e.get_experiment_list_connections_by_connectionmanagement('numProcesses')
elif filter_by == 'CPU':
connections_by_filter = e.get_experiment_list_connections_by_hostsystem('CPU')
elif filter_by == 'CPU Limit':
connections_by_filter = e.get_experiment_list_connections_by_hostsystem('limits_cpu')
elif filter_by == 'Docker Image':
connections_by_filter = e.get_experiment_list_connections_by_parameter('dockerimage')
elif filter_by == 'Experiment Run':
connections_by_filter = e.get_experiment_list_connections_by_parameter('numExperiment')
else:
raise KeyError('filter_by')
return connections_by_filter
def get_connection_colors(color_by: str, filter_connections: list, e: inspector.inspector, inc_lists: bool = False):
"""
Calculates the colors for GIVEN connections using the given color by keyword.
The filtering for connections is done AFTER get_experiment_list_connection_colors()
to keep the same color for each connection.
Returns connection_colors dict like {connection1: #ff0000, ...}
If inc_lists = True, legend_connections and filter_by_connection are returned too.
legend_connections is a list of connections to show in legend.
filter_by_connection is a dict with connections as key and their filter value as value,
for example: {connection1: cl-worker21, connection2: cl-worker4, ...}
Todo: Think about optimizing the filter process.
:param color_by: color by keyword
:param filter_connections: connections to get color for
:param e: evaluate object
:param inc_lists: return legend_connections and filter_by_connection too?
"""
if color_by is None:
# if color_by is None -> get color for each connection
connections_by_filter_sorted = {'temp': e.get_experiment_list_connections()}
else:
# get the corresponding dictionary
connections_by_filter = get_connections_by_filter(color_by, e)
# sort connections_by_filter values like occurrence in e.get_experiment_list_connections()
connections_by_filter_sorted = dict()
for filter_, connections in connections_by_filter.items():
connections_sorted = []
for c in e.get_experiment_list_connections():
if c in connections:
connections_sorted.append(c)
connections_by_filter_sorted[filter_] = connections_sorted
# get the colors for each connection in connections_by_filter_sorted
# like {connection1: ff0000, connection2: ff1010, ...}
connection_colors = e.get_experiment_list_connection_colors(connections_by_filter_sorted)
# filter connection_colors by given connections if necessary
if filter_connections:
connection_colors = {key: connection_colors[key] for key in filter_connections}
if not inc_lists:
return tools.anonymize_dbms(connection_colors)
else:
# filter connections_by_filter_sorted (the value lists)
connections_by_filter_sorted_filtered = dict()
if filter_connections:
# loop through connections_by_filter_sorted and filter the connections lists based on input connections
for filter_ in connections_by_filter_sorted:
if connections_by_filter_sorted[filter_]:
connections_filtered = list(filter(lambda c: c in filter_connections, connections_by_filter_sorted[filter_]))
if connections_filtered:
connections_by_filter_sorted_filtered[filter_] = connections_filtered
else:
# no filter necessary
connections_by_filter_sorted_filtered = connections_by_filter_sorted
# create legend_connections list and filter_by_connection dictionary
if color_by is None:
legend_connections = None
filter_by_connection = None
else:
# use central connection for each filter in legend
legend_connections = [connections[int(len(connections) / 2 - 0.5)]
for filter_, connections in connections_by_filter_sorted_filtered.items()]
# "reverse" the connections_by_filter_sorted_filtered dict to
# receive a dict with connection names as key and their filter as value.
filter_by_connection = dict()
for filter_, connections in connections_by_filter_sorted_filtered.items():
for c in connections:
filter_by_connection[c] = filter_
#return connection_colors, legend_connections, filter_by_connection
return tools.anonymize_dbms(connection_colors), tools.anonymize_dbms(legend_connections), tools.anonymize_dbms(filter_by_connection)
def sort_df_by_list(df: pd.DataFrame, some_list: list) -> pd.DataFrame:
"""
Sort given DataFrame like its indices occur in some_list.
"""
df['temp_order'] = list(map(lambda x: some_list.index(x), df.index))
df.sort_values(by=['temp_order'], inplace=True)
df.pop('temp_order')
return df
def get_new_indices(config: dict, number: int = 1) -> list:
"""
Get variable number of indices not used in config keys.
:param config: dict containing dashboard configuration
:param number: number of new indices
:return: list of new indices
"""
max_index = max(list(map(int, config.keys())) + [-1]) # equals -1 when config ist empty
new_indices = list(range(max_index + 1, max_index + 1 + number))
return new_indices
def predefined_dashboard(connection_indices: list) -> dict:
"""
:param connection_indices: all returned graphs include these as their connection_indices attribute.
:return: dict containing all preset graphs.
"""
common = dict(graph_type='Preset',
connection_indices=connection_indices)
dashboard = {
0: Graph(**common,
preset='heatmap_errors').__dict__,
1: Graph(**common,
preset='heatmap_warnings').__dict__,
2: Graph(**common,
preset='heatmap_result_set_size').__dict__,
3: Graph(**common,
preset='heatmap_total_time').__dict__,
4: Graph(**common,
preset='heatmap_latency_run',
query_aggregate='factor').__dict__,
5: Graph(**common,
preset='heatmap_throughput_run',
query_aggregate='factor').__dict__,
6: Graph(**common,
preset='heatmap_timer_run_factor',
query_aggregate='factor').__dict__,
7: Graph(**common,
preset='barchart_run_drill',
query_aggregate='Mean',
total_aggregate='Mean',
type='timer').__dict__,
8: Graph(**common,
preset='barchart_ingestion_time').__dict__,
}
return dashboard
def investigate_q1(connection_indices: list) -> list:
"""
:param connection_indices: all returned graphs include these as their connection_indices attribute.
:return: list of some predefined graphs for query_id = 1
If the query ids do not start with 1 the query_id needs to be a parameter!
"""
new_graphs = [
Graph(graph_type='Preset',
preset='barchart_run_drill',
query_aggregate='Mean',
query_id=1,
query_index=[0],
type='timer',
connection_indices=connection_indices),
Graph(type='timer',
name='run',
graph_type='Histogram',
query_id=1,
query_index=[0],
colorby='DBMS',
connection_indices=connection_indices),
Graph(type='timer',
name='run',
graph_type='Boxplot',
query_id=1,
query_index=[0],
colorby='DBMS',
connection_indices=connection_indices),
Graph(type='timer',
name='run',
graph_type='Line Chart',
query_id=1,
query_index=[0],
colorby='DBMS',
xaxis='Query',
connection_indices=connection_indices),
]
return new_graphs
class Graph:
"""
Encapsulate methods regarding graph/table creation.
"""
def __init__(self, **kwargs):
"""
Initialize instance attributes with default values and variable number of named arguments.
Arguments override default values.
Valid argument keys are:
('gridRow', 'gridColumn', 'connection_ids', 'connection_indices', 'query_id', 'query_index',
'graph_type', 'type', 'name', 'query_aggregate', 'total_aggregate', 'connection_aggregate',
'warmup', 'cooldown', 'xaxis', 'colorby', 'boxpoints', 'order', 'annotated', 'preset')
"""
# default attributes
attributes = dict(
gridRow=1,
gridColumn=12,
connection_ids=[],
connection_indices=[],
query_id=None,
query_index=[],
graph_type=None,
type=None,
name=None,
query_aggregate=None,
total_aggregate=None,
connection_aggregate=None,
warmup=0,
cooldown=0,
xaxis='Connection',
colorby=None,
boxpoints=None,
order='trace',
annotated=False,
preset=''
)
valid_keys = ['gridRow', 'gridColumn', 'connection_ids', 'connection_indices', 'query_id', 'query_index',
'graph_type', 'type', 'name', 'query_aggregate', 'total_aggregate', 'connection_aggregate',
'warmup', 'cooldown', 'xaxis', 'colorby', 'boxpoints', 'order', 'annotated', 'preset']
# override attributes by given arguments
for key, value in kwargs.items():
if key in valid_keys:
attributes[key] = value
else:
raise KeyError('Invalid key for Graph instance.')
# set instance attributes
for key, value in attributes.items():
setattr(self, key, value)
def calculate_connection_aggregate(self, df: pd.DataFrame, e: inspector.inspector) -> pd.DataFrame:
"""
Calculate the connection aggregate by calling get_aggregated_by_connection() for given DataFrame.
Only connections in connection_ids attribute are taken into account.
:param df: DataFrame to calculate connection aggregate for
:param e: evaluate object
:return: DataFrame with aggregated connections
"""
try:
connections_by_filter = get_connections_by_filter(self.colorby, e)
except KeyError:
connections_by_filter = []
# Filter the connections_by_filter dictionary depending on connection_ids attribute
connections_by_filter_filtered = dict()
if self.connection_ids:
for key in connections_by_filter:
filtered = list(filter(lambda x: x in self.connection_ids, connections_by_filter[key]))
if filtered:
connections_by_filter_filtered[key] = filtered
else:
connections_by_filter_filtered = connections_by_filter # keep all connections
df = e.get_aggregated_by_connection(dataframe=df,
list_connections=connections_by_filter_filtered,
connection_aggregate=self.connection_aggregate)
return df
def calculate_df(self, e: inspector.inspector) -> pd.DataFrame:
"""
Calculate DataFrame depending on instance attributes by calling matching inspector method.
:param e: evaluate object
:return: Result DataFrame
"""
if self.name is None or self.type is None:
raise PreventUpdate
config = dict(type=self.type,
name=self.name,
warmup=int(self.warmup),
cooldown=int(self.cooldown),
dbms_filter=self.connection_ids)
if self.query_id is None: # no specific query selected
config['query_aggregate'] = self.query_aggregate
if self.query_aggregate is None and self.total_aggregate is None:
# raw data not supported yet
raise PreventUpdate
elif self.total_aggregate is None:
df = e.get_aggregated_query_statistics(**config)
else:
config['total_aggregate'] = self.total_aggregate
df = e.get_aggregated_experiment_statistics(**config)
else: # single query selected
df, df2 = e.get_measures_and_statistics(int(self.query_id), **config)
if self.query_aggregate is not None:
df = df2[[self.query_aggregate]]
if self.total_aggregate is not None:
raise PreventUpdate # TODO handle this case
if self.connection_aggregate is not None:
df = self.calculate_connection_aggregate(df, e)
else:
# sort df like in list_connections
df = sort_df_by_list(df, e.get_experiment_list_connections())
return df
def construct_title(self) -> str:
"""
Construct title for a graph/table depending on instance attributes.
"""
preset_to_unit = {'heatmap_errors': 'bool',
'heatmap_warnings': 'bool',
'heatmap_total_time': 'ms',
'barchart_ingestion_time': 's',
'heatmap_result_set_size': ''}
if self.graph_type == 'Preset' and self.preset in preset_to_unit:
title = f'{self.preset}'
unit = preset_to_unit.get(self.preset, '')
if unit:
title += f' [{unit}]'
if self.preset in ['heatmap_errors', 'heatmap_warnings', 'heatmap_result_set_size', 'heatmap_total_time']:
return title
else:
if self.type == 'monitoring':
try:
name = monitor.metrics.metrics[self.name].get('title', self.name)
except KeyError:
name = self.name
else:
name = self.name
if self.graph_type == 'Preset' and self.preset == 'barchart_run_drill':
name = 'run_drilldown'
title = f'{self.type} - {name}'
type_to_unit = {'timer': 'ms',
'latency': 'ms',
'throughput': 'Hz',
'monitoring': ''
}
unit = type_to_unit.get(self.type)
aggregates = {self.query_aggregate, self.total_aggregate, self.connection_aggregate}
if len(aggregates.intersection({'factor', 'cv [%]', 'qcod [%]'})) != 0:
unit = ''
if unit:
title += f' [{unit}]'
if self.query_id is not None:
title += f' | Q{self.query_id} '
title += f' | #connections: {len(self.connection_indices)}'
title += f' | w: {self.warmup}, c: {self.cooldown}'
if self.query_aggregate is not None:
title += f' | run: {self.query_aggregate}'
if self.total_aggregate is not None:
title += f' | query: {self.total_aggregate}'
if self.connection_aggregate is not None:
title += f' | config: {self.connection_aggregate}'
return title
def color_switch(self, axis_no_color: str, df: pd.DataFrame, e: inspector.inspector) -> (dict, pd.DataFrame):
"""
Returns color dict depending on xaxis, colorby and connection_aggregate.
It removes duplicate code in render_go_... functions.
Covers all cases besides:
"self.xaxis = axis_color, self.colorby is NOT None, connection_aggregate is None"
:param axis_no_color: the xaxis setting where color it not useful applicable.
:param df: DataFrame
:param e: evaluate object
:return: color dictionary with df index mapped to colors and the DataFrame itself
"""
if self.xaxis == axis_no_color:
df = df.T
color = dict()
elif self.connection_aggregate is None:
# self.xaxis = !axis_no_color, self.colorby is None, connection_aggregate is None
color = get_connection_colors(self.colorby, self.connection_ids, e)
elif self.colorby is None:
# self.xaxis = !axis_no_color, self.colorby is None, connection_aggregate is NOT None
color = dict()
else:
# self.xaxis = !axis_no_color, self.colorby is NOT None, connection_aggregate is NOT None
connection_colors, legend_connections, filter_by_connection = get_connection_colors(self.colorby,
self.connection_ids,
e, inc_lists=True)
# map filter to color of filter representative (like the case without connection aggregate)
# color_by_filter
color = {filter_by_connection[x]: connection_colors[x] for x in legend_connections}
# keep legend order like the case without connection aggregate
order = [filter_by_connection[x] for x in legend_connections]
df = sort_df_by_list(df, order)
return color, df
def render_go_boxplot(self, df: pd.DataFrame, e: inspector.inspector) -> go.Figure:
"""
Create graph based on given DataFrame and instance attributes.
:return: plotly.go figure object
"""
fig = go.Figure()
common = dict(
boxmean='sd',
hoverinfo='x+y+text',
boxpoints=self.boxpoints,
hovertext=df.columns,
line_width=1
)
if self.boxpoints == "False":
common.update(dict(boxpoints=False))
if self.xaxis == 'Connection' and self.colorby is not None and self.connection_aggregate is None:
# self.xaxis = 'Connection', self.colorby is NOT None, connection_aggregate is None
connection_colors, legend_connections, filter_by_connection = get_connection_colors(self.colorby,
self.connection_ids,
e, inc_lists=True)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Box(x=[index] * len(row),
y=row,
name=filter_by_connection[index],
legendgroup=filter_by_connection[index],
line_color=connection_colors[index],
showlegend=index in legend_connections,
**common)
)
fig.update_traces(quartilemethod="inclusive")
else:
color, df = self.color_switch('Query', df, e)
tools.anonymize_dbms(df)
# df may change
common.update(dict(hovertext=df.columns, showlegend=True))
for index, row in df.iterrows():
fig.add_trace(go.Box(y=row,
name=index,
line_color=color.get(index),
**common))
fig.update_traces(quartilemethod="inclusive")
#
if self.xaxis == 'Connection':
xaxis_title = f'{self.xaxis}'
else:
xaxis_title = 'Query' if self.query_id is None else 'run number'
if len(fig.data) == 1:
xaxis_title = None
fig.update_layout(showlegend=False)
if self.xaxis == 'Connection' and self.colorby is not None:
legend_title_text = self.colorby
else:
legend_title_text = xaxis_title
fig.update_layout(xaxis_title=xaxis_title,
legend_title_text=legend_title_text)
return fig
def render_go_histogram(self, df: pd.DataFrame, e: inspector.inspector) -> go.Figure:
"""
Create graph based on given DataFrame and instance attributes.
:return: plotly.go figure object
"""
fig = go.Figure()
common = dict(
opacity=0.75,
hoverinfo='x+y+text',
)
if self.xaxis == 'Connection' and self.colorby is not None and self.connection_aggregate is None:
# self.xaxis = 'Connection', self.colorby is NOT None, connection_aggregate is None
connection_colors, legend_connections, filter_by_connection = get_connection_colors(self.colorby, self.connection_ids, e,
inc_lists=True)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Histogram(x=row,
name=filter_by_connection[index],
marker_color=connection_colors[index],
hovertext=index,
legendgroup=filter_by_connection[index],
showlegend=index in legend_connections,
**common))
else:
color, df = self.color_switch('Query', df, e)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Histogram(x=row,
name=index,
hovertext=index,
marker_color=color.get(index),
showlegend=True,
**common))
# xaxis_title = ''
# if self.total_aggregate is not None:
# xaxis_title += f'Total {self.total_aggregate} of '
# if self.query_aggregate is not None:
# xaxis_title += f'Query {self.query_aggregate} of '
# xaxis_title += f'{self.type} - {self.name}'
yaxis_title = 'Frequency'
if self.colorby is not None and self.xaxis == 'Connection':
legend_title_text = self.colorby
elif self.xaxis == 'Query' and self.query_id is not None:
legend_title_text = 'run number'
else:
legend_title_text = self.xaxis
if len(fig.data) == 1:
fig.update_layout(showlegend=False)
fig.update_layout(
#xaxis_title=xaxis_title,
yaxis_title=yaxis_title,
legend_title_text=legend_title_text)
return fig
def render_go_line_chart(self, df: pd.DataFrame, e: inspector.inspector) -> go.Figure:
"""
Create graph based on given DataFrame and instance attributes.
:return: plotly.go figure object
"""
fig = go.Figure()
common = dict(hoverinfo='x+y+text', line_width=1)
if self.xaxis == 'Query' and self.colorby is not None and self.connection_aggregate is None:
# self.xaxis = 'Query', self.colorby is NOT None, connection_aggregate is None
connection_colors, legend_connections, filter_by_connection = get_connection_colors(self.colorby, self.connection_ids, e,
inc_lists=True)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Scatter(x=df.columns,
y=row,
name=filter_by_connection[index],
legendgroup=filter_by_connection[index],
line_color=connection_colors[index],
showlegend=index in legend_connections,
hovertext=index,
**common))
else:
color, df = self.color_switch('Connection', df, e)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Scatter(x=df.columns,
y=row,
name=index,
line_color=color.get(index),
showlegend=True,
hovertext=index,
**common))
xaxis_title = ''
# yaxis_title = ''
# if self.total_aggregate is not None:
# yaxis_title += f'Total {self.total_aggregate} of '
# if self.query_aggregate is not None:
# yaxis_title += f'Query {self.query_aggregate} of '
# yaxis_title += f'{self.type} - {self.name}'
if self.xaxis == 'Query':
if self.colorby is not None:
legend_title_text = self.colorby
else:
legend_title_text = 'Connection'
if self.query_id is not None:
xaxis_title = 'run number'
else: # graph_xaxis == 'Connection'
if self.query_id is not None:
legend_title_text = 'run number'
else:
legend_title_text = 'Query'
if len(fig.data) == 1:
fig.update_layout(showlegend=False)
fig.update_layout(xaxis_title=xaxis_title,
# yaxis_title=yaxis_title,
legend_title_text=legend_title_text)
return fig
def render_go_bar_chart(self, df: pd.DataFrame, e: inspector.inspector) -> go.Figure:
"""
Create graph based on given DataFrame and instance attributes.
:return: plotly.go figure object
"""
fig = go.Figure()
if self.xaxis == 'Query' and self.colorby is not None and self.connection_aggregate is None:
# self.xaxis = 'Query', self.colorby is NOT None, connection_aggregate is None
connection_colors, legend_connections, filter_by_connection = get_connection_colors(self.colorby, self.connection_ids, e,
inc_lists=True)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Bar(x=df.columns,
y=row.values,
name=filter_by_connection[index],
legendgroup=filter_by_connection[index],
marker_color=connection_colors[index],
showlegend=index in legend_connections,
hoverinfo='x+y+text',
hovertext=index))
legend_title_text = self.colorby
else:
color, df = self.color_switch('Connection', df, e)
tools.anonymize_dbms(df)
for index, row in df.iterrows():
fig.add_trace(go.Bar(x=df.columns,
y=row.values,
name=index,
marker_color=color.get(index),
showlegend=True,
hoverinfo='x+y+text',
hovertext=index))
# yaxis_title = ''
# if self.total_aggregate is not None:
# yaxis_title += f'Total {self.total_aggregate} of '
# if self.query_aggregate is not None:
# yaxis_title += f'Query {self.query_aggregate} of '
#
# yaxis_title += f'{self.type} - {self.name}'
xaxis_title = self.xaxis
fig.update_layout(xaxis={'categoryorder': self.order})
fig.update_layout(xaxis_title=xaxis_title,
#yaxis_title=yaxis_title,
#legend_title_text=legend_title_text,
barmode='group')
return fig
def render_go_heatmap(self, df: pd.DataFrame, text: str = None) -> go.Figure:
"""
Create graph based on given DataFrame and instance attributes.
:param df:
:param text: optional hover text to show in go.Heatmap
:return: plotly.go figure object
"""
tools.anonymize_dbms(df)
# manual rotate
if self.xaxis == 'Connection':
df = df.T
if text is not None:
text = text.T
# workaround for old graphs which do not have annotated attribute
try:
logging.debug(self.annotated)
except AttributeError:
self.annotated = False
if self.annotated:
df_round = df.round(decimals=3)
ff_fig = ff.create_annotated_heatmap(
x=[str(x) for x in list(df_round.columns)],
y=[str(x) for x in list(df_round.index)],
z=df_round.values.tolist(),
showscale=True)
fig = go.Figure(ff_fig)
fig.layout.xaxis.side = 'bottom'
fig.layout.xaxis.type = 'category'
fig.layout.yaxis.type = 'category'
else:
fig = go.Figure(
data=go.Heatmap(
x=[str(x) for x in list(df.columns)],
y=[str(x) for x in list(df.index)],
z=df.values.tolist(),
hoverongaps=False,
text=text
)
)
fig.layout.xaxis.type = 'category'
fig.layout.yaxis.type = 'category'
return fig
def render_go_preset(self, e: inspector.inspector) -> (go.Figure, pd.DataFrame):
"""
Render preset figure based on instance attributes.
:param e: evaluate object
:return: preset figure and the underlying DataFrame
"""
if 'heatmap' in self.preset:
df_text = None
if self.preset in ['heatmap_result_set_size', 'heatmap_total_time']:
if self.preset == 'heatmap_result_set_size':
# evaluate.get_total_resultsize()
df = e.get_total_resultsize_normalized()
elif self.preset == 'heatmap_total_time':
df = e.get_total_times(self.connection_ids)
#e.get_total_times_normalized()
#e.get_total_times_relative()
if self.query_id:
df = df[[f'Q{self.query_id}']]
if self.connection_ids:
df = df[df.index.isin(self.connection_ids)]
if self.connection_aggregate is not None:
df = self.calculate_connection_aggregate(df, e)
elif self.preset in ['heatmap_errors', 'heatmap_warnings']:
self.annotated = False
if self.preset == 'heatmap_errors':
df = e.get_total_errors().replace({False: 0, True: 1})
if self.query_id:
df = df[[f'Q{self.query_id}']]
if self.connection_ids:
df = df[df.index.isin(self.connection_ids)]
df_text = df.replace({0: '', 1: 'error'})
for index, row in df_text.iterrows():
for column, value in row.items():
if value:
try:
numQuery = int(column.replace('Q', ''))
error = e.get_error(numQuery=numQuery, connection=index)
except:
error = 'ERROR'
df_text.at[index, column] = error
elif self.preset == 'heatmap_warnings':
df = e.get_total_warnings()#.replace({False: 0, True: 1})
if self.query_id:
df = df[[f'Q{self.query_id}']]
if self.connection_ids:
df = df[df.index.isin(self.connection_ids)]