-
Notifications
You must be signed in to change notification settings - Fork 9
/
pairplot.py
2204 lines (1944 loc) · 107 KB
/
pairplot.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
import dash
from dash import Dash, dash_table, dcc, html
from dash.dependencies import Input, Output, State, MATCH, ALL
from frontend_api import app as Flask_app
import plotly.graph_objects as go
import pandas as pd
import urllib
import math
import json
import time
import os
import requests
import logging
logging.basicConfig(level=logging.INFO)
from datetime import datetime
import sys
backend_root = os.getenv("MATCHER_BACKEND_URL")
external_frontend_root = os.getenv("EXTERNAL_FRONTEND_URL")
external_backend_root = os.getenv("EXTERNAL_BACKEND_URL")
def df_round(value):
if type(value) != type(5.5): return value
if value > 100:
value = int(value)
elif value > 10:
value = round(value, 1)
elif value > 0.1:
value = round(value, 2)
elif value > 0.01:
value = round(value, 3)
elif value > 0.001:
value = round(value, 4)
elif value < 0.0001:
value = round(value, 7)
return value
def smiles_to_image_link(smiles, x, y, scaleImage='False'):
return '![{}]({}/smilesToImage?smiles={}&x={}&y={}&scaleImage={})'.format(smiles, external_backend_root, urllib.parse.quote(smiles, safe=''), x, y, scaleImage)
def pair_to_aligned_image_links(A_smiles, B_smiles, pattern, x, y):
return (
'![{}]({}/smilesToImage_aligned?smiles={}&pattern={}&x={}&y={})'.format(A_smiles, external_backend_root, urllib.parse.quote(A_smiles, safe=''), urllib.parse.quote(pattern, safe=''), x, y),
'![{}]({}/smilesToImage_aligned?smiles={}&pattern={}&x={}&y={})'.format(B_smiles, external_backend_root, urllib.parse.quote(B_smiles, safe=''), urllib.parse.quote(pattern, safe=''), x, y)
)
def get_individual_transforms_df(df):
# Image will get bigger if > 10 atoms in molecule, up to a limit of 2x the size defined below
df['FROM'] = df['FROM'].apply(lambda x: smiles_to_image_link(x, 100, 50, scaleImage='True'))
df['TO'] = df['TO'].apply(lambda x: smiles_to_image_link(x, 100, 50, scaleImage='True'))
for column in df.columns:
if '_fold-change' in column or '_delta' in column:
df[column] = df[column].apply(lambda x: df_round(x))
df.sort_values(by='pairs', inplace=True, ascending=False)
return df
def get_individual_transforms_table(df, default_x_label, default_y_label):
initial_data = df.to_dict('records')
transform_table = dash_table.DataTable(
id='table_transforms',
# Dash seems to only wrap text at spaces or - marks
# But property column names can be long with multiple _, and Dash is setting widths of these columns to be narrow sometimes
columns=[dict(name=i.replace('_', ' '), id=i, type='text', presentation='markdown') for i in df.columns if i not in ['id']],
data = initial_data,
fixed_rows={'headers': True},
style_header={
'whiteSpace': 'normal',
'height': 'auto',
'backgroundColor': '#86818a',
'color': '#FFFFFF',
'fontWeight': 'bold',
'textAlign': 'left',
'fontSize': 15,
},
editable=False,
filter_action="native",
sort_action="native",
sort_mode='multi',
row_selectable='multi',
row_deletable=False,
selected_rows=[],
page_action='native',
page_current=0,
page_size=15,
markdown_options={'link_target': '_blank', 'html': True},
style_data_conditional=(get_styles(df, statistic='median')),
style_table={'height': 500, 'maxHeight': 500, 'overflowY': 'auto'},
active_cell={'row': 0, 'column': 0, 'row_id': initial_data[0]['id'], 'column_id': 'FROM'} if len(df.index) > 0 else None
)
return transform_table
def get_group_by_fragment_df(df):
for column in df.columns:
if '_fold-change' in column or '_delta' in column or r'% transforms' in column:
df[column] = df[column].apply(lambda x: df_round(x))
columns = df.columns.tolist()
# Image will get bigger if > 10 atoms in molecule, up to a limit of 2x the size defined below
df['TO'] = df['TO'].apply(lambda x: smiles_to_image_link(x, 100, 50, scaleImage='True'))
df['FROM'] = df['FROM'].apply(lambda x: ' '.join(list(map(lambda y: smiles_to_image_link(y,100,50,scaleImage='True'), x))))
stats_columns = []
for column in columns:
if 'median' in column or r'%' in column:
stats_columns.append(column)
# Control the order, from left to right, in which the columns will be displayed in the transform table
# 'id' column will not be displayed, because it is specifically omitted during dash datatable generation
new_df = df[['id', 'TO', 'transforms', 'pairs'] + stats_columns + ['FROM']]
new_df.sort_values(by='transforms', inplace=True, ascending=False)
return new_df
def get_group_by_fragment_table(df, default_x_label, default_y_label):
initial_data_dict = df.to_dict('records')
transform_table = dash_table.DataTable(
id='table_transforms',
# Dash seems to only wrap text at spaces or - marks
# But property column names can be long with multiple _, and Dash is setting widths of these columns to be narrow sometimes
columns=[dict(name=i.replace('_', ' '), id=i, type='text', presentation='markdown') for i in df.columns if i not in ['id', 'rule_id_array']],
data = initial_data_dict,
#fixed_columns={'headers': True, 'data': 4},
fixed_rows={'headers': True},
editable=False,
filter_action="native",
sort_action="native",
sort_mode='multi',
row_selectable='multi',
row_deletable=False,
selected_rows=[],
page_action='native',
page_current= 0,
page_size= 20,
markdown_options={'link_target': '_blank', 'html': True},
style_data_conditional=(get_styles(df, statistic='median median')),
style_table={'height': 500, 'maxHeight': 500, 'overflowY': 'auto', 'minWidth': '100%'},
style_header={
'whiteSpace': 'normal',
'height': 'auto',
'backgroundColor': '#86818a',
'color': '#FFFFFF',
'fontWeight': 'bold',
'textAlign': 'left',
'fontSize': 12,
},
style_cell={
'textAlign': 'left',
'minWidth': '100px'#, 'width': '180px', 'maxWidth': '180px',
},
active_cell={'row' : 0, 'column' : 0, 'row_id' : initial_data_dict[0]['id'], 'column_id' : 'TO'}
)
return transform_table
def get_styles(df, statistic = ''):
styles = []
for column in df.columns:
prop_name = None
if 'fold-change' in column:
styles += data_bars_diverging(df, column)
prop_name = column[:-12]
elif 'delta' in column:
prop_name = column[:-6]
if 'EPSA' in column:
styles += data_bars_diverging(df, column, log_or_linear='linear', col_min=-30, col_max=30, midpoint=0)
elif 'PXR' in column:
styles += data_bars_diverging(df, column, log_or_linear='linear', col_min=-50, col_max=50, midpoint=0)
elif 'logD' in column:
styles += data_bars_diverging(df, column, log_or_linear='linear', col_min=-3, col_max=3, midpoint=0)
else:
styles += data_bars_diverging(df, column, log_or_linear='linear', col_min=-10, col_max=10, midpoint=0)
elif r'% transforms' in column:
styles += data_bars_diverging(df, column, log_or_linear='linear', col_min = 0, col_max = 100, midpoint = 50)
if prop_name is not None:
styles += data_bars_diverging(df, r'% transforms (+' + prop_name + ')', log_or_linear='linear', col_min=0, col_max=100, midpoint=50)
#styles += data_bars_diverging(df, r'% transforms (+' + prop_name + ')', log_or_linear='linear', col_min=0, col_max=100, midpoint=50, color_above='#0343ab', color_below='#ff9900')
return styles
# Makes the statistics appear with red / green bars in the transform table
# Adapted from https://dash.plotly.com/datatable/conditional-formatting
# Made the ranges increase exponentially so that fold-change data is appropriately colored / scaled
def data_bars_diverging(df, column, log_or_linear='log', col_min=0.1, col_max=10, midpoint=1, color_above='#3D9970', color_below='#FF4136'):
n_bins = 100
bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
col_max = col_max
col_min = col_min
# For linear scale, which we intend to apply to deltas, midpoint of 0 means nothing changes: B - A = 0
# For log scale, which we intend to apply to fold-changes, midpoint of 1 means nothing changes: B / A = 1
midpoint = midpoint
ranges = [col_min]
num = col_min
if log_or_linear == 'log':
# Exponential growth factor, such that compounding col_min by the factor 100 times will equal the col_max
# If our midpoint is halfway (on the log scale) between col_min and col_max, then the above factor should give us 50 bins below the midpoint, and 50 bins above, spaced logarithmically
factor = (col_max / col_min) ** (1/100)
# For example, if we consider a 0.1x fold-change to be a full red bar, and a 10x change to be a full green bar, then we use the below settings:
# For col_min = 0.1, col_max = 10, midpoint = 1: then the factor = 1.047128
for i in range(1, 101):
num = num * factor
ranges.append(num)
elif log_or_linear == 'linear':
# For example: if we're looking at EPSA, and we consider +30 units (or -30 units) to be an off the chart change,
# resulting in a full green bar, or full red bar, respectively, then the total_span is 60 units
increment = (col_max - col_min) / n_bins
for i in range(1, 101):
num += increment
ranges.append(num)
else:
raise ValueError("log_or_linear must be 'log' or 'linear'")
len_bounds = len(bounds)
styles = []
for i in range(1, len_bounds + 1):
if i < len_bounds:
min_bound = ranges[i - 1]
max_bound = ranges[i]
min_bound_percentage = bounds[i - 1] * 100
max_bound_percentage = bounds[i] * 100
style = {
'if': {
'filter_query': (
'{{{column}}} >= {min_bound}' +
(' && {{{column}}} < {max_bound}' if (i < len_bounds - 1) else '')
).format(column=column, min_bound=min_bound, max_bound=max_bound),
'column_id': column
},
'paddingBottom': 2,
'paddingTop': 2
}
# Create a single style for the case where the row value is less than the lower threshold, coloring the bar as -100% red
elif i == len_bounds:
min_bound, max_bound = ranges[0], ranges[0]
min_bound_percentage, max_bound_percentage = 0, 0
style = {
'if': {
'filter_query': '{{{column}}} < {min_bound}'.format(column=column, min_bound=min_bound),
'column_id': column
},
'paddingBottom': 2,
'paddingTop': 2
}
if max_bound > midpoint:
background = (
"""
linear-gradient(90deg,
white 0%,
white 50%,
{color_above} 50%,
{color_above} {max_bound_percentage}%,
white {max_bound_percentage}%,
white 100%)
""".format(
max_bound_percentage=max_bound_percentage,
color_above=color_above
)
)
else:
background = (
"""
linear-gradient(90deg,
white 0%,
white {min_bound_percentage}%,
{color_below} {min_bound_percentage}%,
{color_below} 50%,
white 50%,
white 100%)
""".format(
min_bound_percentage=min_bound_percentage,
color_below=color_below
)
)
style['background'] = background
styles.append(style)
return styles
# Takes in a row from the dataframe containing MMPs (1 pair per row)
# Turns that row into a Dash DataTable containing the structures, IDs, properties, and fold-changes for those properties
def generate_pair_tables(rows: list):
# keys:
# A, B, constant, A_ID, B_ID, A_prop, B_prop, prop_fold-change, prop_delta
pair_tables = []
for row in rows:
try:
A_image, B_image = pair_to_aligned_image_links(row['a'], row['b'], row['constant'], 300, 150)
except Exception as exc:
print(exc)
A_image = smiles_to_image_link(row['a'], 300, 150)
B_image = smiles_to_image_link(row['b'], 300, 150)
_column = ['Structure', 'ID']
A_column = [A_image, row['a_id']]
B_column = [B_image, row['b_id']]
__column = ['', 'Fold-changes']
# For some properties we calculated deltas and not fold-changes
# First look for fold-changes, and add them, while keeping track of seen delta props; then add deltas underneath
delta_props = set()
for key in row.keys():
# Infer property names, e.g. if key = A_Papp, then key[2:] = Papp is a property
if key[0:2] == 'a_' and key != 'a_id':
if key[2:] + '_delta' in row.keys():
delta_props.add(key[2:])
continue
_column.append(key[2:])
A_column.append(row[key])
B_column.append(row['b_' + key[2:]])
__column.append(row[key[2:] + '_fold-change'])
# If no fold-change props were found, change the column header, otherwise append a blank row with a new header for Deltas
if len(__column) == 2:
__column[1] = 'Deltas'
elif len(delta_props) > 0:
_column.append('')
A_column.append('')
B_column.append('')
__column.append('Deltas')
for prop in delta_props:
_column.append(prop)
A_column.append(row['a_' + prop])
B_column.append(row['b_' + prop])
__column.append(row[prop + '_delta'])
pair_df = pd.DataFrame({
'_' : _column,
'A' : A_column,
'B' : B_column,
'__' : __column
})
pair_table = dash_table.DataTable(
id=str(len(pair_tables)),
columns=[dict(name=i, id=i, type='text', presentation='markdown') for i in ['_', 'A', 'B', '__']],
data = pair_df.dropna().to_dict('records'),
style_header = {'display': 'none'},
style_cell={
'whiteSpace': 'normal',
'height': 'auto',
},
row_selectable=False,
markdown_options={'link_target': '_blank', 'html': True},
style_table={'overflowX' : 'auto'},
css=[{
'selector': 'tr:first-child',
'rule': 'display: none',
}]
)
pair_tables.append(pair_table)
return pair_tables
def base10_to_color_hex(number):
hex_number = format(number, 'X')
hex_number_for_color = '#' + '0'*(6 - len(hex_number)) + hex_number
return hex_number_for_color
def get_prop_labels(props, property_metadata={}):
prop_labels = []
for prop in props:
if not prop:
continue
# display_name is the name for the property that the user will see
# In contrast, prop represents the name of the property in the database, property_name.name column
display_name = property_metadata[prop]['display_name']
default_change_axis_type = default_A_axis_type = 'Log'
# database_base indicates whether the prop is stored as log, negative_log, or raw in the DB compound_property.value column
database_base = property_metadata[prop]['base']
average_label = 'Average(log) ' + display_name if database_base in ('log', 'negative_log') else 'Average ' + display_name
frontend_base = property_metadata[prop]['display_base']
units = property_metadata[prop].get('display_unit')
change_type = property_metadata[prop]['change_displayed']
change_label = display_name + '_' + change_type
# Below is necessary to prevent SQL from attempting subtraction
change_type = change_type.replace('-', '_')
"""
# EPSA, logD_HPLC_pH7, and PXR should not be transformed from their stored values
elif prop in ['EPSA', 'logD_HPLC_pH7', 'PXR']:
average_label = 'Average ' + prop
change_type = 'delta'
change_label = prop + '_delta'
default_change_axis_type = 'Linear'
if prop in ['logD_HPLC_pH7', 'PXR']:
default_A_axis_type = 'Linear'
"""
labels = {
'prop': prop,
'A': 'A_' + display_name,
'B': 'B_' + display_name,
'average_label': average_label,
'change_type': change_type,
'change_label': change_label,
'default_change_axis_type': default_change_axis_type,
'default_A_axis_type': default_A_axis_type,
'base': frontend_base,
'units': units,
}
prop_labels.append(labels)
return prop_labels
def rename_column_headers(headers, minmax=False, property_metadata={}):
# We can't completely control case in the column headers retrieved from asyncpg via the API, nor use dashes (-) in normal postgres names, therefore we rename headers as desired here
renamed = []
rename_map = {'rule_id': 'id', 'from_smiles':'FROM', 'from_smiles_env':'FROM', 'from_smiles_array':'FROM', 'from_smiles_env_array':'FROM',
'to_smiles':'TO', 'to_smiles_env':'TO', 'pair_count':'pairs', 'transform_count': 'transforms'}
original_case_names = sorted(property_metadata.keys(), key=len, reverse=True)
for header in headers:
for name in original_case_names:
if name.lower() in header:
# Use the user-defined display_name rather than the name from the DB property_name.name column
if minmax == False:
header = header.replace(name.lower(), property_metadata[name]['display_name'])
elif minmax == True:
header = header.replace(name.lower(), property_metadata[name]['display_name'].lower())
# Only use the longest name replacement, prevent further replacement by substrings of the longest name
# above, we sorted original_case_names to have the longest names first
break
if header in rename_map:
renamed.append(rename_map[header])
elif 'fold_change' in header:
renamed.append(header.replace('fold_change', 'fold-change'))
elif 'percent_increased_' in header:
prop = header.split('_', 2)[2]
renamed.append(f"% transforms (+{prop})")
else:
renamed.append(header)
return renamed
def map_colors_to_ids(aggregation_type, df, environment_included):
# Generate randomly distributed colors for plot
# Convert hex number to integer: this is the largest hex color value we want to use, because any larger hex color values are often too light-colored
six_hex_base10_limit = int('9aaaaa', 16)
num_colors = df['id'].nunique()
if num_colors == 0:
return {}
step = int(six_hex_base10_limit / num_colors)
all_colors = set(range(0, six_hex_base10_limit, step))
# Tuple of color hex codes, ('#000000', ... , '#XXXXXX')
all_colors = list(map(base10_to_color_hex, all_colors))
colors_mapped_to_ids = {}
current_color = 0
if aggregation_type == 'individual_transforms' and not environment_included:
# ID will either be a Numpy int64 integer (rule_id), or a from_smiles_env + '_' + to_smiles_env string
type_convert = lambda x: int(x)
else:
type_convert = lambda x: x
for row_idx in range(len(df.index)):
row_id = type_convert(df.iloc[row_idx]['id'])
if row_id not in colors_mapped_to_ids:
colors_mapped_to_ids[row_id] = {'color': all_colors[current_color]}
current_color += 1
if aggregation_type == 'group_by_fragment':
# It also benefits us to store the mappings from TO_smiles to rule_id_array in a concise format (as opposed to having to load all data from the transform table), which will be used in scatterplot generation
if not environment_included:
colors_mapped_to_ids[row_id]['rule_id_array'] = df.iloc[row_idx]['rule_id_array']
else:
colors_mapped_to_ids[row_id]['from_env_array'] = df.iloc[row_idx]['FROM']
return colors_mapped_to_ids
def get_range_filter_args(rf_names, min_rfs, max_rfs, display_name_to_property_name):
rf_args = []
for name, rf_min, rf_max in zip(rf_names, min_rfs, max_rfs):
assert name[0:2] in ('A_', 'B_')
compound, display_name_prop = name.split('_', 1)
# e.g. converting display_name_prop='CYP3A4_IC50_uM' to value in DB column property_name.name='CYP3A4'
prop = display_name_to_property_name[display_name_prop]
if rf_min not in [None, 'None']:
rf_args.append({'compound': compound, 'property_name': prop, 'operator': '>=', 'value': rf_min})
if rf_max not in [None, 'None']:
rf_args.append({'compound': compound, 'property_name': prop, 'operator': '<=', 'value': rf_max})
return rf_args
def create_dash_app(dataframe = None, requests_pathname_prefix='/dash/', aggregation_type=None, snapquery_dict=None, snapfilter_dict=None, flask_server=None):
if flask_server is not None:
# USING routes_pathname_prefix IS KEY FOR THE DASH INTERFACE TO LOAD FROM FLASK WITH THIS SETUP
app_dash = Dash(__name__, assets_folder="css/dash/" , routes_pathname_prefix=requests_pathname_prefix, prevent_initial_callbacks=True, server=flask_server, serve_locally=False)
else:
raise Exception("A Flask server must be provided as an argument")
# The initially loaded layout will only show submit button.
# Clicking on one of these two buttons will obtain data, then instantiate and initialize the rest of the elements
# Subsequent clicking on one of these two buttons will overwrite all the previously instantiated elements
def generate_layout():
layout = html.Div([
dcc.Store(id='resize_iframe_dummy_output', data=['{}']),
dcc.Store(id='error_message_dummy_output', data=['{}']),
dcc.Store(id='property_metadata', data={}),
dcc.Store(id='display_name_to_property_name', data={}),
# When the query is running, or data is loading, show a loading icon in place of the submit button, so user doesn't spam queries by accident
dcc.Loading(
[
dcc.Store(id='input_data', data=['{}']),
dcc.Store(id='query_data', data=['{}']),
dcc.Store(id='pair_data', data=['{}']),
html.Div(
[
html.Div(
[
html.Button("Submit query", id="submit_button", style={'backgroundColor': '#7a0dd9', 'color':'#ffffff', 'border-style': 'none'}),
],
style={'display': 'inline-block'}
),
],
style={'display': 'flex', 'justify-content': 'center', 'margin': '0', 'padding': '0'}
),
],
type="circle"
),
html.Br(), html.Br(), html.Br(),
# Here is where we will place the rest of the Dash app elements, after the pair_data is loaded
html.Div(id='output_div',
children=[]
),
])
return layout
# pair_data flows in from submit button (via DB query)
# Once we have the data, we can use the data to initialize all of the output elements
@app_dash.callback(
[Output('output_div', 'children')],
[Input('pair_data', 'data')],
[State('query_data', 'data'),
State('property_metadata', 'data'),
State('display_name_to_property_name', 'data'),]
)
def instantiate_output_elements(pair_data, query_data, property_metadata, display_name_to_property_name):
pair_data = json.loads(pair_data)
if "observations" in pair_data:
# This means that something went wrong with the query, so we are returning an empty layout
# We need to return a pair_tables div, because the iframe resizing callback depends on this div as an input
return [html.Div(children=[
html.Div(
['no_output'],
id = 'pair_tables',
style={'display': 'none'}
)])
]
query_id = pair_data["query_id"]
snapquery_dict = json.loads(query_data)
aggregation_type = snapquery_dict['advanced_options']['aggregation_type']
"""
# identifier associated with rows in the transform table
if aggregation_type == 'individual_transforms':
identifier = 'rule_id'
elif aggregation_type == 'group_by_fragment':
identifier = 'TO'
else:
raise ValueError("invalid query_type, query_type must be 'individual_transforms' or 'group_by_fragment'")
"""
if snapquery_dict['snapfilter_string'] != '':
snapfilter_exists = True
else:
snapfilter_exists = False
# Initialize range filters key because we reference it during range_filters initialization, even if there's no snapfilter
snapfilter = {
'range_filters': {},
'transform_row_ids': [],
}
rf_args = []
if snapfilter_exists:
snapfilter_list = snapquery_dict['snapfilter_string'].split(';')
transform_row_ids = snapfilter_list[4].split(',')
# We migrated from Oracle to Postgres in Nov 2021, causing snapfilters with id < 322 to have transform_row_ids that are outdated
# Therefore we need to not use these ids, if snapfilter id is less than 322
if transform_row_ids != [''] and int(snapquery_dict['snapfilter_id']) > 321:
if aggregation_type == 'individual_transforms' and '_' not in transform_row_ids[0]:
transform_row_ids = [int(x) for x in transform_row_ids]
else:
transform_row_ids = []
# Example range_filters_list is 'A_Papp,None,20@B_Papp,20,None'
range_filters_list = snapfilter_list[5].split('@')
range_filters_dict = {}
if range_filters_list != ['']:
rf_names, min_rfs, max_rfs = [0]*len(range_filters_list), [0]*len(range_filters_list), [0]*len(range_filters_list)
for i, rf_name_min_max in enumerate(range_filters_list):
rf_names[i], min_rfs[i], max_rfs[i] = rf_name_min_max.split(',')
# for applying filter values to UI elements
range_filters_dict[rf_names[i]] = {
'min': float(min_rfs[i]) if min_rfs[i] != 'None' else None,
'max': float(max_rfs[i]) if max_rfs[i] != 'None' else None,
}
rf_args = get_range_filter_args(rf_names, min_rfs, max_rfs, display_name_to_property_name)
snapfilter = {
'default_x_label': snapfilter_list[0],
'default_y_label': snapfilter_list[1],
'default_x_type': snapfilter_list[2],
'default_y_type': snapfilter_list[3],
'transform_row_ids': transform_row_ids,
'range_filters': range_filters_dict
}
separator = '-'
# Use a set in case the user selects the same properties between required and optional properties
all_props = set(snapquery_dict["REQUIRED_properties"].split(",") + snapquery_dict["OPTIONAL_properties"].split(","))
prop_labels = get_prop_labels(all_props, property_metadata=property_metadata)
# Set the default axis labels on the plot, which are populated in the two dropdown menus
if snapfilter_exists:
default_x_label, default_y_label, default_x_type, default_y_type = (snapfilter['default_x_label'], snapfilter['default_y_label'], snapfilter['default_x_type'], snapfilter['default_y_type'])
initial_agg_prop_labels = []
for prop_label in prop_labels:
if default_x_label in prop_label.values() or default_y_label in prop_label.values():
initial_agg_prop_labels.append(prop_label)
else:
initial_agg_prop_labels = prop_labels[0:2]
if len(prop_labels) == 1:
default_x_label = prop_labels[0]['A']
default_x_type = prop_labels[0]['default_A_axis_type']
default_y_label = prop_labels[0]['change_label']
default_y_type = prop_labels[0]['default_change_axis_type']
elif len(prop_labels) > 1:
default_x_label = prop_labels[0]['change_label']
default_x_type = prop_labels[0]['default_change_axis_type']
default_y_label = prop_labels[1]['change_label']
default_y_type = prop_labels[1]['default_change_axis_type']
# On load, we aggregate statistics based on the first 2 user-selected properties (or 1, if only 1 was selected)
agg_args = {
'query_id': query_id,
'aggregation_type': aggregation_type,
'range_filters': rf_args,
'statistics': [
{
'statistic': 'median',
'property_name': prop['prop'],
'change_type': prop['change_type'],
'base': prop['base'],
'units': prop['units'],
} for prop in initial_agg_prop_labels
]
}
schema = snapquery_dict['schema']
table_data = requests.post(backend_root + f'/aggregate_transforms?schema={schema}', data=json.dumps(agg_args))
table_data = table_data.json()
minmax = table_data['minmax']
# The minmax columns were named within postgres, which restricts certain characters
# We need the minmax column names to match the names in the x/y dropdowns, therefore we need to rename some columns
renamed_minmax_headers = rename_column_headers(list(minmax.keys()), minmax=True, property_metadata=property_metadata)
minmax = dict(zip(renamed_minmax_headers, minmax.values()))
# Detect whether the environment was included in the aggregation, which is only needed for multicut queries
environment_included = False
for column in table_data['column_headers']:
if 'smiles_env' in column:
environment_included = True
break
columns = rename_column_headers(table_data['column_headers'], property_metadata=property_metadata)
table_data = table_data['rows']
df = pd.DataFrame(table_data, columns=columns)
if environment_included:
if aggregation_type == 'individual_transforms':
df['id'] = df['FROM'].apply(lambda x: str(x) + '_') + df['TO']
elif aggregation_type == 'group_by_fragment':
df['id'] = df['TO'].copy()
else:
# By default for individual_transforms with environment_included == False, the API call will return a column with 'rule_id' header which gets changed to 'id' header by rename_column_headers
if aggregation_type == 'group_by_fragment':
df['id'] = df['TO'].copy()
colors_mapped_to_ids = map_colors_to_ids(aggregation_type, df, environment_included)
# Approach with dropdowns, radiobuttons, and callback scatter plotting adapted from https://dash.plotly.com/interactive-graphing
#### UI Component definitions
x_y_dropdown_options = []
for label in ['change_label', 'A', 'B', 'average_label']:
for prop in prop_labels:
x_y_dropdown_options.append({'label': prop[label], 'value': prop[label]})
x_Dropdown = dcc.Dropdown(
id='crossfilter-xaxis-column',
options = x_y_dropdown_options,
value=default_x_label
)
x_RadioItems = dcc.RadioItems(
id='crossfilter-xaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value=default_x_type,
labelStyle={'display': 'inline-block', 'marginTop': '5px'}
)
y_Dropdown = dcc.Dropdown(
id='crossfilter-yaxis-column',
options = x_y_dropdown_options,
value=default_y_label
)
y_RadioItems = dcc.RadioItems(
id='crossfilter-yaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value=default_y_type,
labelStyle={'display': 'inline-block', 'marginTop': '5px'}
)
main_scatterplot = dcc.Graph(
id='pairPlot'
)
range_filters = []
range_filter_options = []
for label in ['A', 'B']:
for prop in prop_labels:
range_filter_options.append(prop[label])
for column in range_filter_options:
range_filters.append(
(
column,
dcc.Input(
id={'type': 'min_range_filter', 'index': column},
type='number',
debounce=True,
style={'width': '45%', 'display': 'inline-block'},
value=snapfilter['range_filters'][column]['min'] if column in snapfilter['range_filters'] else None,
),
dcc.Input(
id={'type': 'max_range_filter', 'index': column},
type='number',
debounce=True,
style={'width':'45%', 'display': 'inline-block'},
value=snapfilter['range_filters'][column]['max'] if column in snapfilter['range_filters'] else None,
)
)
)
range_filter_names = json.dumps(range_filter_options)
range_filters_dropdown = dcc.Dropdown(
id='range_filters_dropdown',
options=[{'label': name, 'value': name} for name in range_filter_options],
value=range_filters[0][0]
)
if aggregation_type == 'individual_transforms':
initialize_transform_table = get_individual_transforms_table
get_updated_transform_table_df = get_individual_transforms_df
elif aggregation_type == 'group_by_fragment':
initialize_transform_table = get_group_by_fragment_table
get_updated_transform_table_df = get_group_by_fragment_df
else:
raise ValueError("aggregation_type has invalid value, must be 'individual_transforms' or 'group_by_fragment'")
df = get_updated_transform_table_df(df)
transform_table = initialize_transform_table(df, default_x_label, default_y_label)
initial_agg_data = df.to_dict('records')
total_row_count = len(initial_agg_data)
# Above we calculated num_colors based on having a unique color for each ID in the transform_table
# This number will shrink if we are looking at any combination of properties other than the single most common property in the query
initial_total_row_count = df['id'].nunique()
num_rows_displayed_Plaintext = html.Plaintext(id='num_rows_displayed_plaintext', children='Displaying ' + str(initial_total_row_count) + ' out of ' + str(initial_total_row_count) + ' rows', style={'font-size': '15px', 'font-weight': 'bold'})
children = [
dcc.Store(id='snapfilter', data=json.dumps(snapfilter)),
dcc.Store(id='colors_mapped_to_ids', data=[json.dumps(colors_mapped_to_ids)]),
# Use in the callback that updates transform_table, to enforce initialization of row filtration, using snapfilter['transform_row_ids']
#dcc.Store(id='snapfilter_applied', data= [{'snapfilter_applied': False if snapfilter_exists else True}]),
dcc.Store(id='snapfilter_applied', data= False if snapfilter_exists else True),
html.Button("not_intended_to_display", id="start_highlight_first_row", n_clicks=0, style={'display' : 'none'}),
html.Button("not_intended_to_display", id="finish_highlight_first_row", n_clicks=0, style={'display' : 'none'}),
dcc.Store(id='identifier', data='id'),
dcc.Store(id='agg_data', data=json.dumps(initial_agg_data)),
dcc.Store(id='minmax', data=json.dumps(minmax)),
html.Div(
[
html.Div(
[
html.Div(
[
num_rows_displayed_Plaintext,
dcc.Store(id='displayed_row_count', data=json.dumps(total_row_count)),
dcc.Store(id='total_row_count', data=json.dumps(total_row_count)),
],
style={'display': 'inline-block', 'margin-right': '10px'}
),
html.Div(
[
html.Button("Reset All Filters", id="reset_all_filters_button"),
],
style={'display': 'inline-block'}
)
],
style={'display': 'inline-block'},
),
html.Div(
[
html.Div(
[
html.Plaintext('Copy shareable link:', style={'font-size': '15px', 'color': '#8334eb', 'font-weight': 'bold', 'display': 'inline-block', 'margin-right': '10px'}),
dcc.Loading(
[
dcc.Clipboard(
id="copy_link_clipboard", content='Error occurred during copying, try once more', className='button',
style={'color': '#ffffff', 'background-color': '#8334eb', 'border': '1px solid #8334eb', 'margin-right': '10px'}
),
html.Button("Enumerate Checked Rows", id="enumerate_button", style={'display': 'inline-block', 'margin-right': '10px', 'backgroundColor': '#eb8334', 'color':'#ffffff', 'border-style':'none'}),
dcc.Download(id="download_enumerations"), dcc.Store(id="selected_row_data", data=['{}']),
html.Button("Download Raw Data", id="download_button", style={'display': 'inline-block'}), dcc.Download(id="download-dataframe-csv"),
],
type='circle',
style={'display': 'inline-block'},
parent_style={'display': 'inline-block'},
),
],
style={'display': 'inline-block'}
)
],
style={'display': 'inline-block'},
),
],
style={'display': 'flex', 'justify-content': 'space-between', 'margin': '0', 'padding': '0'}
),
html.Div(
[
html.Plaintext('Select rows:', style={'font-size': '15px', 'font-weight': 'bold', 'display': 'inline-block', 'margin-right': '10px'}),
html.Button("Select All", id="select_all_button", style={'display': 'inline-block'}),
html.Button("Deselect All", id="deselect_all_button", style={'display': 'inline-block'})
],
),
html.Div(id='range_filters_div',
children=[
html.Div([
html.Div(
[html.Plaintext('Filter rows:', style={'font-size': '15px', 'font-weight': 'bold'})],
style={'display': 'inline-block', 'margin-right': '10px'}
),
html.Div(
[html.Button("Filter selected", id="filter_rows_button")],
style={'display': 'inline-block'}
),
html.Div(
[html.Button("Reset", id="reset_rows_filter_button")],
style={'display': 'inline-block'}
),
], style={'display': 'inline-block'}),
html.Div([
html.Div(
[html.Plaintext('Range Filters:', style = {'display': 'inline-block', 'vertical-align': 'middle', 'font-size': '15px', 'font-weight': 'bold', 'margin-right': '10px'})],
style={'width': '15%', 'display': 'inline-block'}
),
html.Div(
[range_filters_dropdown],
style={'width': '30%', 'display': 'inline-block', 'vertical-align': 'middle', 'margin-right' : '10px'}
),
] + [
html.Div(
id={'type': 'range_filter_div', 'index': range_filters_name},
style={'width': '20%', 'display': 'inline-block', 'margin-right': '10px'} if range_filters_name == range_filters[0][0] else {'display': 'none'},
children=[range_filters_min, html.Plaintext(' - ', style={'width': '10%', 'font-weight': 'bold', 'display': 'inline-block'}), range_filters_max]
) for (range_filters_name, range_filters_min, range_filters_max) in range_filters
] + [
html.Div(
[html.Button("Apply", id="apply_filters_button")],
style={'display': 'inline-block'}
),
html.Div(
[html.Button("Reset All", id="reset_filters_button")],
style={'display': 'inline-block'}
),
], style={'display': 'inline-block'})
],
style={'display': 'flex', 'justify-content': 'space-between', 'margin': '0', 'padding': '0'}
),
dcc.Store(id='row_selection_filter', data=[]),
dcc.Store(id='original_row_mappings', data={}),
dcc.Store(id='range_filter_names', data=range_filter_names),
html.Div(
[transform_table],
),
html.Br(), html.Br(),
html.Div(
[
html.Div(
[
html.Div(
[
html.Div(
[html.Plaintext('X-Axis', style = {'position': 'relative', 'top': '50%', 'transform': 'translateY(-50%)', 'font-size': '15px', 'font-weight': 'bold'})],
style={'width': '8%', 'display': 'inline-block'}
),
html.Div(
[x_Dropdown],
style={'width': '24%', 'display': 'inline-block'}
),
html.Div(
[x_RadioItems],
style={'width': '16%', 'display': 'inline-block', 'position': 'relative', 'top': '50%', 'transform': 'translateY(-50%)'}
),
html.Div(
[],
style={'width': '2%', 'display': 'inline-block'}
),
html.Div(
[html.Plaintext('Y-Axis', style = {'position': 'relative', 'top': '50%', 'transform': 'translateY(-50%)', 'font-size': '15px', 'font-weight': 'bold'})],
style={'width': '8%', 'display': 'inline-block'}
),
html.Div(
[y_Dropdown],
style={'width': '24%', 'display': 'inline-block'}
),
html.Div(
[y_RadioItems],
style={'width': '16%', 'display': 'inline-block', 'position': 'relative', 'top': '50%', 'transform': 'translateY(-50%)'}
)
],
),
html.Div(
[main_scatterplot],
style={'width': '98%', 'display': 'inline-block'}
)
],
style={'width': '49%', 'display': 'inline-block', 'vertical-align' : 'top'},
),
html.Div(
[
html.Div(
[html.Plaintext('To see matched pairs, left click on plot and drag-select points', style = {'position': 'relative', 'top': '50%', 'transform': 'translateY(-50%)', 'font-size': '15px', 'font-weight': 'bold'})],
style={'width': '8%', 'display': 'inline-block'}
),
html.Div(
[html.Button('Clear', id='clearButton', n_clicks=0)]
),
html.Div(
[],
id = 'pair_tables'
)
],
style={'width': '49%', 'display': 'inline-block', 'vertical-align' : 'top'}
)
],
style={'display': 'flex', 'justify-content': 'start', 'margin': '0', 'padding': '0'}
),
]
return [html.Div(children=children)]
app_dash.layout = generate_layout
# Collect user-entered data from matcher.html form
app_dash.clientside_callback(
"""
function (n_clicks) {
// This callback will always fire on page load, in order to support automatic query firing of snapshot-based queries
// However, if we loaded the page without any snapshot-based query, then the fields will be empty; in that case, don't confuse the user with an error message
// This block disables itself after the initial page load, so subsequently the user will get error messages if they try to submit an incomplete form
if (parent.suppress_initial_errors === true) {
parent.suppress_initial_errors = false;