fyrizi commited on
Commit
aa73f51
·
verified ·
1 Parent(s): 45c1fae

Delete main/src/reporting_bokeh_samples.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. main/src/reporting_bokeh_samples.py +0 -834
main/src/reporting_bokeh_samples.py DELETED
@@ -1,834 +0,0 @@
1
- import warnings
2
- import math
3
- import functools
4
- import collections
5
-
6
- from bokeh.layouts import column, row
7
- from bokeh.models import ColumnDataSource, TableColumn, DataTable, HTMLTemplateFormatter, Select, \
8
- CategoricalColorMapper, HoverTool, LinearColorMapper, ColorBar, FixedTicker, NumberFormatter
9
- from bokeh.models.widgets import Panel, Div
10
- from bokeh.plotting import figure
11
- import numpy as np
12
- from bokeh.transform import transform
13
- from bokeh_ui import BokehUi
14
- from data_category import DataCategory
15
-
16
-
17
-
18
- def len_batch(batch):
19
- """
20
-
21
- Args:
22
- batch: a data split or a `collections.Sequence`
23
-
24
- Returns:
25
- the number of elements within a data split
26
- """
27
- if isinstance(batch, (collections.Sequence, torch.Tensor)):
28
- return len(batch)
29
-
30
- assert isinstance(batch, collections.Mapping), 'Must be a dict-like structure! got={}'.format(type(batch))
31
-
32
- for name, values in batch.items():
33
- if isinstance(values, (list, tuple)):
34
- return len(values)
35
- if isinstance(values, torch.Tensor) and len(values.shape) != 0:
36
- return values.shape[0]
37
- if isinstance(values, np.ndarray) and len(values.shape) != 0:
38
- return values.shape[0]
39
- return 0
40
-
41
-
42
-
43
- def safe_lookup(dictionary, *keys, default=None):
44
- """
45
- Recursively access nested dictionaries
46
- Args:
47
- dictionary: nested dictionary
48
- *keys: the keys to access within the nested dictionaries
49
- default: the default value if dictionary is ``None`` or it doesn't contain
50
- the keys
51
- Returns:
52
- None if we can't access to all the keys, else dictionary[key_0][key_1][...][key_n]
53
- """
54
- if dictionary is None:
55
- return default
56
-
57
- for key in keys:
58
- dictionary = dictionary.get(key)
59
- if dictionary is None:
60
- return default
61
-
62
- return dictionary
63
-
64
-
65
- class PanelDataSamplesTabular(BokehUi):
66
- """
67
- Display tabular data
68
-
69
- Configuration options:
70
- default/with_column_title_rotation: 1 or 0
71
- """
72
- def __init__(self, options, name, data, data_types, type_categories, title='Tabular'):
73
- with_column_title_rotation = int(safe_lookup(
74
- options.config,
75
- name,
76
- 'default',
77
- 'with_column_title_rotation',
78
- default='1')) > 0
79
-
80
- ui, self.table = process_data_samples__tabular(
81
- options,
82
- name,
83
- data,
84
- data_types,
85
- type_categories,
86
- title=title,
87
- with_column_title_rotation=with_column_title_rotation
88
- )
89
- super().__init__(ui)
90
-
91
- def update_data(self, options, name, data, data_types, type_categories):
92
- source = self.table.source
93
-
94
- # make sure we do not populate very large data to a table. Remove
95
- # the large datasets (if not, the data is sent to the client, which
96
- # may result in slow rendering time)
97
- data = filter_large_data(options, data)
98
-
99
- for key in source.column_names:
100
- if key not in data:
101
- # some data is missing, just do not update the table yet
102
- return
103
- self.table.source.update(data=data)
104
-
105
-
106
- def process_data_samples__tabular(options, name, data, data_types, type_categories, title, with_column_title_rotation=True):
107
- """
108
- Create a tabular panel of the data & types
109
-
110
- Args:
111
- options:
112
- data: a dictionary of (key, values)
113
- data_types: a dictionary of (key, type) indicating special type of ``key``
114
- title: the title of the panel to be displayed
115
-
116
- Returns:
117
- a panel
118
- """
119
- image_style = """
120
- img
121
- {
122
- height:%dpx;
123
- width:%dpx;
124
- }
125
- """ % (options.image_size, options.image_size)
126
-
127
- template = f"""
128
- <div>
129
- <style>
130
- {image_style}
131
- </style>
132
- <img
133
- src=<%= value %>
134
- ></img>
135
- </div>
136
- """
137
-
138
- with_images = False
139
- columns = []
140
- for key in data.keys():
141
- type = data_types.get(key)
142
- if type is not None and 'BLOB_IMAGE' in type:
143
- with_images = True
144
- c = TableColumn(field=key, title=key, formatter=HTMLTemplateFormatter(template=template))
145
- else:
146
- type_category = type_categories[key]
147
- table_kargs = {}
148
- if type_category == DataCategory.Continuous:
149
- table_kargs['formatter'] = NumberFormatter(format='0,0[.000]')
150
-
151
- c = TableColumn(field=key, title=key, **table_kargs)
152
- columns.append(c)
153
-
154
- # filter out data
155
- filtered_data = filter_large_data(options, data)
156
- data_source = ColumnDataSource(filtered_data)
157
-
158
- if with_column_title_rotation:
159
- # custom CSS to slightly rotate the column header
160
- # and draw text outside their respective columns
161
- # to improve readability. TODO That could be improved
162
- div = Div(text=f"""
163
- <style>
164
- .eporting_table_{name} .slick-header-column {{
165
- background-color: transparent;
166
- background-image: none !important;
167
- transform:
168
- rotate(-10deg)
169
- }}
170
-
171
- .bk-root .slick-header-column.ui-state-default {{
172
- height: 40px;
173
- overflow: visible;
174
- vertical-align: bottom;
175
- line-height: 4.4;
176
- }}
177
- </style>
178
- """)
179
- div.visible = False # hide the div to avoid position issues
180
- else:
181
- div = None
182
-
183
- row_height = options.font_size
184
- if with_images:
185
- row_height = options.image_size
186
-
187
- data_table = DataTable(
188
- source=data_source,
189
- columns=columns,
190
- row_height=row_height,
191
- #fit_columns=True,
192
- css_classes=[f"reporting_table_{name}"])
193
-
194
- columns = [data_table, div] if div is not None else [data_table]
195
-
196
- return Panel(child=column(*columns, sizing_mode='stretch_both'), title=title), data_table
197
-
198
-
199
- def scatter(all_data, groups, scatter_name, type_category):
200
- if type_category in (DataCategory.DiscreteUnordered, DataCategory.DiscreteOrdered):
201
- # discrete types, without ordering. Split the data into sub-groups
202
- # need to use global `unique_values` so that the groups are synchronized
203
- scatter_values = all_data[scatter_name]
204
- unique_values = set(scatter_values)
205
- if type_category == DataCategory.DiscreteOrdered:
206
- unique_values = sorted(unique_values)
207
-
208
- final_groups = []
209
- for group in groups:
210
- data = np.asarray(all_data[scatter_name])[group]
211
-
212
- current_groups = []
213
- for id, value in enumerate(unique_values):
214
- indices = np.where(data == value)
215
- current_groups.append(group[indices])
216
- final_groups.append(current_groups)
217
- return final_groups, [{'value': value, 'type': 'discrete'} for value in unique_values]
218
- elif type_category == DataCategory.Continuous:
219
- all_scatter_values = np.asarray(all_data[scatter_name])[np.concatenate(groups)]
220
- value_min = all_scatter_values.min()
221
- value_max = all_scatter_values.max()
222
- return [[g] for g in groups], [
223
- {'value_min': value_min, 'value_max': value_max, 'type': 'continuous', 'scatter_name': scatter_name}]
224
- else:
225
- raise NotImplementedError()
226
-
227
-
228
- def group_coordinate(options, data, group, group_layout_y, group_layout_x):
229
- """
230
- Create a coordinate system for each group, independently of the other groups
231
- """
232
- if group_layout_y['type'] == 'discrete' and group_layout_x['type'] == 'discrete':
233
- nb_columns = math.ceil(math.sqrt(len(group)))
234
- coords_x = (np.arange(len(group)) % nb_columns) * options.image_size
235
- coords_y = (np.arange(len(group)) // nb_columns) * options.image_size
236
- coords = np.stack((coords_x, coords_y), axis=1)
237
- return coords
238
-
239
- if group_layout_y['type'] == 'continuous' and group_layout_x['type'] == 'discrete':
240
- nb_rows = len(group)
241
- scatter_name = group_layout_y['scatter_name']
242
- coords_x = np.random.rand(nb_rows) * options.image_size * 0.75
243
- coords_y = np.asarray(data[scatter_name])[group]
244
- coords = np.stack((coords_x, coords_y), axis=1)
245
- return coords
246
-
247
- if group_layout_x['type'] == 'continuous' and group_layout_y['type'] == 'discrete':
248
- nb_rows = len(group)
249
- scatter_name = group_layout_x['scatter_name']
250
- coords_y = np.random.rand(nb_rows) * options.image_size * 0.75
251
- coords_x = np.asarray(data[scatter_name])[group]
252
- coords = np.stack((coords_x, coords_y), axis=1)
253
- return coords
254
-
255
- if group_layout_x['type'] == 'continuous' and group_layout_y['type'] == 'continuous':
256
- scatter_name_x = group_layout_x['scatter_name']
257
- scatter_name_y = group_layout_y['scatter_name']
258
- coords_x = np.asarray(data[scatter_name_x])[group]
259
- coords_y = np.asarray(data[scatter_name_y])[group]
260
- coords = np.stack((coords_x, coords_y), axis=1)
261
- return coords
262
-
263
- raise NotImplementedError()
264
-
265
-
266
- def sync_groups_coordinates(options, data_x, data_y, groups, groups_layout_y, groups_layout_x):
267
- """
268
- Up to that point, each group had sample coordinates calculated independently from
269
- each other. Here consolidate all the subcoordinate system into a global one
270
- """
271
- if groups_layout_x[0]['type'] == 'discrete':
272
- for x in range(groups.shape[1] - 1):
273
- groups_at_x = np.concatenate(groups[:, x])
274
- min_value_for_next_group = data_x[groups_at_x].max() + options.image_size + \
275
- options.style.category_margin * options.image_size
276
-
277
- for y in range(groups.shape[0]):
278
- group = groups[y, x + 1]
279
- if len(group) == 0:
280
- # there are no sample for this group, simply skip it
281
- continue
282
- min_group = data_x[group].min()
283
- shift = max(min_value_for_next_group - min_group, 0)
284
- data_x[group] += shift
285
- elif groups_layout_x[0]['type'] == 'continuous':
286
- pass
287
- else:
288
- raise NotImplementedError()
289
-
290
- if groups_layout_y[0]['type'] == 'discrete':
291
- for y in range(groups.shape[0] - 1):
292
- groups_at_y = np.concatenate(groups[y, :])
293
- min_value_for_next_group = data_y[groups_at_y].max() + options.image_size + \
294
- options.style.category_margin * options.image_size
295
-
296
- for x in range(groups.shape[1]):
297
- group = groups[y + 1, x]
298
- if len(group) == 0:
299
- # there are no sample for this group, simply skip it
300
- continue
301
- min_group = data_y[group].min()
302
- shift = max(min_value_for_next_group - min_group, 0)
303
- data_y[group] += shift
304
- elif groups_layout_y[0]['type'] == 'continuous':
305
- pass
306
- else:
307
- raise NotImplementedError()
308
-
309
-
310
- def filter_large_data(options, data):
311
- """
312
- remove very large data, this will be communicated to the client and this is
313
- very slow!
314
- """
315
- filtered_data = collections.OrderedDict()
316
- for name, values in data.items():
317
- if isinstance(values[0], np.ndarray) and values[0].size > options.data_samples.max_numpy_display:
318
- # data is too large and take too long to display so remove it
319
- filtered_data[name] = ['...'] * len(values)
320
- warnings.warn(f'numpy array ({name}) is too large ({values[0].size}) and has been discarded')
321
- continue
322
- filtered_data[name] = values
323
- return filtered_data
324
-
325
-
326
- def render_data(
327
- options, data, data_types, type_categories, scatter_x, scatter_y, binning_x_axis,
328
- binning_selection_named, binning_selection_integral, color_by, color_scheme,
329
- icon, label_with, layout):
330
- previous_figure = None
331
-
332
- while len(layout.children) >= 2:
333
- layout.children.pop()
334
-
335
- binning_selection_named.visible = False
336
- binning_selection_integral.visible = False
337
- if len(binning_x_axis.value) > 0 and binning_x_axis.value != 'None':
338
- scatter_values = data[binning_x_axis.value]
339
- unique_values = set(list(scatter_values))
340
- unique_values = list(sorted(unique_values))
341
-
342
- # update the binning selection tool
343
- binning_type = type_categories.get(binning_x_axis.value)
344
- selection = 'None'
345
- if binning_type == DataCategory.DiscreteUnordered or binning_type == DataCategory.DiscreteOrdered:
346
- binning_selection_named.visible = True
347
- binning_selection_integral.visible = False
348
-
349
- selection_values = ['None'] + [str(v) for v in unique_values]
350
- binning_selection_named.options = selection_values[::-1] # reversed (e.g., last epoch is first choice)
351
- if binning_selection_named.value not in binning_selection_named.options:
352
- binning_selection_named.value = binning_selection_named.options[0]
353
- selection = binning_selection_named.value
354
- elif binning_type == DataCategory.Continuous:
355
- raise NotImplementedError()
356
-
357
- if selection == 'None':
358
- groups = []
359
- for value in unique_values:
360
- group = np.where(np.asarray(scatter_values) == value)
361
- groups.append((f'group={value}, ', group))
362
- else:
363
- # need to convert to original data type
364
- value = scatter_values[0]
365
- if not isinstance(value, np.ndarray):
366
- value = np.asarray(value)
367
- selection_value = np.asarray(selection, dtype=value.dtype)
368
- indices = np.where(np.asarray(scatter_values) == selection_value)
369
- groups = [(f'group={selection}, ', indices)]
370
- else:
371
- nb_data = len_batch(data)
372
- groups = [('', [np.arange(nb_data)])]
373
-
374
- # remove very large data, this will be communicated to the client and this is
375
- # very slow!
376
- data = filter_large_data(options, data)
377
-
378
- x_range = None
379
- y_range = None
380
- figs = []
381
- for group_n, (group_name, group) in enumerate(groups):
382
- # copy the data: there were some display issues if not
383
- subdata = {name: list(np.asarray(value)[group[0]]) for name, value in data.items()}
384
- data_source = ColumnDataSource(subdata)
385
- nb_data = len(group[0])
386
- group = [np.arange(nb_data)]
387
-
388
- layout_children = render_data_frame(
389
- group_name, f'fig_{group_n}', options, data_source,
390
- subdata,
391
- group, data_types, type_categories, scatter_x,
392
- scatter_y, color_by, color_scheme, icon, label_with, previous_figure)
393
-
394
- if x_range is None:
395
- x_range = layout_children[0].children[0].x_range
396
- y_range = layout_children[0].children[0].y_range
397
- else:
398
- layout_children[0].children[0].x_range = x_range
399
- layout_children[0].children[0].y_range = y_range
400
-
401
- for c in layout_children:
402
- figs.append(c)
403
-
404
- layout.children.append(row(*figs, sizing_mode='stretch_both'))
405
-
406
-
407
- def render_data_frame(fig_title, fig_name, options, data_source, data, groups, data_types, type_categories, scatter_x,
408
- scatter_y, color_by, color_scheme, icon, label_with, previous_figure):
409
- print('render command STARTED, nb_samples=', len(groups[0]))
410
- # re-create a new figure each time... there are too many bugs currently in bokeh
411
- # to support dynamic update of the data
412
- fig = prepare_new_figure(options, data, data_types)
413
- layout_children = [row(fig, sizing_mode='stretch_both')]
414
-
415
- nb_data = len_batch(data)
416
- fig.title.text = f'{fig_title}Samples selected: {len(groups[0])}'
417
- fig.renderers.clear()
418
- fig.yaxis.visible = False
419
- fig.xaxis.visible = False
420
-
421
- data_x_name = f'{fig_name}_data_x'
422
- data_y_name = f'{fig_name}_data_y'
423
-
424
- if data_x_name not in data_source.column_names:
425
- data_source.add(np.zeros(nb_data, np.float32), data_x_name)
426
- data_source.add(np.zeros(nb_data, np.float32), data_y_name)
427
- data_source.add([None] * nb_data, 'color_by')
428
-
429
- fig.xaxis.axis_label = scatter_x.value
430
- fig.yaxis.axis_label = scatter_y.value
431
-
432
- if len(scatter_x.value) > 0 and scatter_x.value != 'None':
433
- scatter_x = scatter_x.value
434
- assert scatter_x in data, f'column not present in data! c={scatter_x}'
435
- else:
436
- scatter_x = None
437
-
438
- if len(scatter_y.value) > 0 and scatter_y.value != 'None':
439
- scatter_y = scatter_y.value
440
- assert scatter_y in data, f'column not present in data! c={scatter_y}'
441
- else:
442
- scatter_y = None
443
-
444
- if scatter_x is not None:
445
- groups, groups_layout_x = scatter(
446
- data,
447
- groups,
448
- scatter_x,
449
- type_category=type_categories[scatter_x])
450
- groups = groups[0]
451
- else:
452
- # consider all the points as x
453
- groups_layout_x = [{'value': '', 'type': 'discrete'}]
454
-
455
- if scatter_y is not None:
456
- groups, groups_layout_y = scatter(
457
- data,
458
- groups,
459
- scatter_y,
460
- type_category=type_categories[scatter_y])
461
- else:
462
- # consider all the points as y
463
- groups = [[g] for g in groups]
464
- groups_layout_y = [{'value': '', 'type': 'discrete'}]
465
-
466
- if len(color_by.value) > 0 and color_by.value != 'None':
467
- color_by = color_by.value
468
- else:
469
- color_by = None
470
-
471
- if color_by is not None and type_categories[color_by] == DataCategory.Continuous:
472
- color_scheme.visible = True
473
- else:
474
- color_scheme.visible = False
475
-
476
- # in case we have array of 3D instead of 2D+list (if samples have exactly the same in the 2 groups)
477
- # we need to transpose only the first and second but NOT the third
478
- groups = np.asarray(groups)
479
- groups_transpose = list(range(len(groups.shape)))
480
- tmp = groups_transpose[0]
481
- groups_transpose[0] = groups_transpose[1]
482
- groups_transpose[1] = tmp
483
- groups = groups.transpose(groups_transpose)
484
-
485
- data_x = np.zeros(nb_data, dtype=np.float)
486
- data_y = np.zeros(nb_data, dtype=np.float)
487
- for y in range(groups.shape[0]):
488
- for x in range(groups.shape[1]):
489
- group = groups[y, x]
490
- group_layout_y = groups_layout_y[y]
491
- group_layout_x = groups_layout_x[x]
492
-
493
- c = group_coordinate(options, data, group, group_layout_y, group_layout_x)
494
- data_x[group] = c[:, 0]
495
- data_y[group] = c[:, 1]
496
-
497
- sync_groups_coordinates(options, data_x, data_y, groups, groups_layout_y, groups_layout_x)
498
-
499
- data_source.data[data_x_name] = data_x
500
- data_source.data[data_y_name] = data_y
501
-
502
- if color_by is not None:
503
- # prepare the colors
504
- if 'discrete' in type_categories[color_by].value:
505
- colors_all_values = np.asarray(data[color_by], dtype=str)
506
- color_unique_values = list(set(colors_all_values))
507
- if options.style.sorted_legend:
508
- color_unique_values = sorted(color_unique_values)
509
- color_unique_palette_ints = np.random.randint(0, 255, [len(color_unique_values), 3])
510
- color_unique_palette_hexs = ['#%0.2X%0.2X%0.2X' % tuple(c) for c in color_unique_palette_ints]
511
-
512
- color_mapper = CategoricalColorMapper(
513
- factors=color_unique_values, # must have string
514
- palette=color_unique_palette_hexs)
515
-
516
- # could not use the simple legend mechanism (was messing up the figure.
517
- # Instead resorting to another figure). This has the added benefit that we can
518
- # zoom in and out of the legend in case we have many categories
519
- sub_fig = figure(
520
- title='Labels',
521
- width=options.style.tool_window_size_x, height=options.style.tool_window_size_y,
522
- x_range=(-0.1, 1), y_range=(0, 26),
523
- tools='pan,reset',
524
- toolbar_location='above')
525
- y_text = 25 - np.arange(0, len(color_unique_values))
526
- sub_fig.circle(x=0, y=y_text, size=15, color=color_unique_palette_hexs)
527
- sub_fig.axis.visible = False
528
- sub_fig.xgrid.visible = False
529
- sub_fig.ygrid.visible = False
530
- sub_fig.text(x=0, y=y_text, text=color_unique_values, x_offset=15, y_offset=6 // 2, text_font_size='6pt')
531
- sub_fig.sizing_mode = 'fixed'
532
- layout_children.append(sub_fig)
533
-
534
- elif 'continuous' in type_categories[color_by].value:
535
- colors_all_values = np.asarray(data[color_by])
536
- palette = color_scheme.value
537
- min_value = colors_all_values.min()
538
- max_value = colors_all_values.max()
539
- color_mapper = LinearColorMapper(palette=palette, low=min_value, high=max_value)
540
-
541
- bar = ColorBar(
542
- title=color_by,
543
- label_standoff=10,
544
- title_standoff=10,
545
- color_mapper=color_mapper,
546
- location=(0, 0),
547
- ticker=FixedTicker(ticks=np.linspace(min_value, max_value, 5))
548
- )
549
- fig.add_layout(bar, "right")
550
-
551
- else:
552
- raise NotImplementedError()
553
-
554
- data_source.data['color_by'] = colors_all_values
555
- fill_color = transform('color_by', color_mapper)
556
- else:
557
- data_source.data['color_by'] = [None] * nb_data
558
- fill_color = 'blue'
559
-
560
- if len(icon.value) > 0 and (icon.value != 'Icon' and icon.value != 'Dot'):
561
- # the images do NOT support tooltips yet in bokeh, instead, overlay a transparent rectangle
562
- # that will display the tooltip
563
- units = 'data'
564
- if 'continuous' in [groups_layout_y[0]['type'], groups_layout_x[0]['type']]:
565
- # make the size of the image fixed so that when we have
566
- # many points close by, we can zoom in to isolate the samples
567
- units = 'screen'
568
- else:
569
- # keep aspect ration ONLY when we display collection of
570
- # images. If we have continuous axis, we do NOT want to
571
- # constrain the value of the axis by another axis
572
- fig.match_aspect = True
573
-
574
- fig.image_url(url=icon.value, x=data_x_name, y=data_y_name,
575
- h=options.image_size, h_units=units,
576
- w=options.image_size, w_units=units,
577
- anchor="center", source=data_source)
578
-
579
- fig.rect(x=data_x_name, y=data_y_name, width=options.image_size, height=options.image_size, width_units=units,
580
- height_units=units, source=data_source, fill_alpha=0, line_alpha=0)
581
-
582
- if color_by is not None:
583
- fig.rect(
584
- source=data_source,
585
- x=data_x_name,
586
- y=data_y_name,
587
- width=options.image_size - options.style.color_by_line_width, # TODO data space mixed with screen space
588
- height=options.image_size - options.style.color_by_line_width,
589
- line_color=fill_color,
590
- fill_color=None,
591
- line_width=options.style.color_by_line_width,
592
- width_units=units, height_units=units,
593
- )
594
-
595
- elif icon.value == 'Icon':
596
- fig.oval(x=data_x_name, y=data_y_name, width=options.image_size, height=options.image_size, width_units='data',
597
- height_units='data', source=data_source, fill_color=fill_color)
598
- elif icon.value == 'Dot':
599
- fig.circle(x=data_x_name, y=data_y_name, size=5, source=data_source, line_color='black', fill_color=fill_color)
600
- else:
601
- raise NotImplementedError()
602
-
603
- if scatter_x and groups_layout_x[0]['type'] == 'discrete':
604
- ticks = []
605
- ticks_label = []
606
- for x in range(groups.shape[1]):
607
- coords_x = data_x[np.concatenate(groups[:, x])]
608
- if len(coords_x) > 0:
609
- min_value = coords_x.min()
610
- max_value = coords_x.max()
611
- center_value = int(min_value + max_value) // 2
612
-
613
- ticks += [center_value]
614
- ticks_label += [groups_layout_x[x]['value']]
615
-
616
- fig.xaxis.visible = True
617
- fig.xaxis.ticker = ticks
618
- fig.xaxis.major_label_overrides = {t: str(name) for t, name in zip(ticks, ticks_label)}
619
- fig.xaxis.major_label_orientation = math.pi / 4
620
- elif scatter_x and groups_layout_x[0]['type'] == 'continuous':
621
- fig.xaxis.visible = True
622
- else:
623
- fig.xaxis.visible = False
624
-
625
- if scatter_y and groups_layout_y[0]['type'] == 'discrete':
626
- ticks = []
627
- ticks_label = []
628
- for y in range(groups.shape[0]):
629
- coords_y = data_y[np.concatenate(groups[y, :])]
630
- if len(coords_y) > 0:
631
- min_value = coords_y.min()
632
- max_value = coords_y.max()
633
- center_value = int(min_value + max_value) // 2
634
-
635
- ticks += [center_value]
636
- ticks_label += [groups_layout_y[y]['value']]
637
-
638
- fig.yaxis.visible = True
639
- fig.yaxis.ticker = ticks
640
- fig.yaxis.major_label_overrides = {t: str(name) for t, name in zip(ticks, ticks_label)}
641
- fig.yaxis.major_label_orientation = math.pi / 4
642
- elif scatter_y and groups_layout_y[0]['type'] == 'continuous':
643
- fig.yaxis.visible = True
644
- else:
645
- fig.yaxis.visible = False
646
-
647
- print('render command DONE')
648
- return layout_children
649
-
650
-
651
- def make_custom_tooltip(options, data, data_types):
652
- tips = []
653
- for key in data.keys():
654
- # create a custom tooltip to display images
655
- t = data_types.get(key)
656
- if t is not None and 'BLOB_IMAGE' in t:
657
- tip = f"""
658
- <div style="opacity: 1.0;">
659
- <img
660
- src="@{key}" width="100%"
661
- border="2"
662
- </img>
663
- <span>{key}</span>
664
- </div>
665
- """
666
- tips.append(tip)
667
- else:
668
- tips.append(f'<div><span style="">{key}: @{key}</span></div>')
669
-
670
- # this style make sure that a single tooltip is displayed at once. If
671
- # many samples overlap, it may be really slow to render these
672
- # and they will be out of the screen anyway
673
- div_style = """
674
- <style>
675
- .bk-tooltip>div:not(:first-child) {display:none;}
676
- </style>
677
- """
678
- return '<div>' + div_style + '\n'.join(tips) + '</div>'
679
-
680
-
681
- def prepare_new_figure(options, data, data_types):
682
- tools = 'pan,wheel_zoom,reset'
683
- f = figure(
684
- title='',
685
- tools=tools,
686
- active_scroll='wheel_zoom',
687
- toolbar_location='above',
688
- height=900,
689
- width=900,
690
- name='data_samples_fig'
691
- )
692
-
693
- hover_tool = HoverTool(tooltips=make_custom_tooltip(options, data, data_types))
694
- f.add_tools(hover_tool)
695
-
696
- f.xgrid.visible = False
697
- f.ygrid.visible = False
698
- return f
699
-
700
-
701
- class PanelDataSamplesScatter(BokehUi):
702
- def __init__(self, options, name, data, data_types, type_categories):
703
- self.scatter_x_axis = Select(title='Scatter X Axis', name='scatter_x_axis')
704
- self.scatter_y_axis = Select(title='Scatter Y Axis', name='scatter_y_axis')
705
- self.color_by = Select(title='Color by', name='color_by')
706
- self.color_scheme = Select(title='Color scheme', name='color_scheme')
707
- self.binning_x_axis = Select(title='Binning X Axis', name='binning_x_axis')
708
-
709
- self.binning_selection_named = Select(title='Binning selection', name='binning_selection_named')
710
- self.binning_selection_named.visible = True
711
-
712
- self.binning_selection_integral = Select(title='Binning selection', name='binning_selection_integral')
713
- self.binning_selection_integral.visible = False
714
-
715
- self.label_with = Select(title='Label with', name='label_with')
716
- self.icon = Select(title='Display with', name='icon')
717
-
718
- controls_list = [
719
- self.scatter_x_axis,
720
- self.scatter_y_axis,
721
- self.color_by,
722
- self.color_scheme,
723
- self.binning_x_axis,
724
- self.binning_selection_named,
725
- self.binning_selection_integral,
726
- self.label_with,
727
- self.icon
728
- ]
729
- controls = column(controls_list, name='PanelDataSamplesScatter_controls')
730
- controls.sizing_mode = "fixed"
731
-
732
- self.update_controls(options, name, data, data_types, type_categories)
733
-
734
- layout = row(controls, sizing_mode='stretch_both')
735
-
736
- self.last_data = data
737
- self.last_data_types = data_types
738
- self.last_type_categories = type_categories
739
-
740
- update_partial = functools.partial(
741
- render_data,
742
- options=options,
743
- scatter_x=self.scatter_x_axis,
744
- scatter_y=self.scatter_y_axis,
745
- binning_x_axis=self.binning_x_axis,
746
- binning_selection_named=self.binning_selection_named,
747
- binning_selection_integral=self.binning_selection_integral,
748
- color_by=self.color_by,
749
- color_scheme=self.color_scheme,
750
- icon=self.icon,
751
- label_with=self.label_with,
752
- layout=layout,
753
- )
754
-
755
- for control in controls_list:
756
- control.on_change('value', lambda attr, old, new: self._update())
757
-
758
- self.refresh_view_fn = update_partial
759
- self._update()
760
-
761
- super().__init__(ui=Panel(child=layout, title='Scatter'))
762
-
763
- def _update(self):
764
- # record the last used values. If we keep
765
- # only the last n rows of data, we need to
766
- # keep these variables updated!
767
-
768
- self.refresh_view_fn(
769
- data=self.last_data,
770
- data_types=self.last_data_types,
771
- type_categories=self.last_type_categories
772
- )
773
-
774
- def update_controls(self, options, name, data, data_types, type_categories):
775
- data_names = list(sorted(data.keys()))
776
- values = ['None'] + data_names
777
- values_integral = ['None'] + [n for n in data_names if type_categories[n] in (
778
- DataCategory.DiscreteUnordered, DataCategory.DiscreteOrdered)]
779
-
780
- def populate_default(control, values, control_name, default='None'):
781
- control.options = values
782
- if control.value == '':
783
- default = safe_lookup(options.config, name, 'default', control_name, default=default)
784
- control.value = default
785
-
786
- populate_default(self.scatter_x_axis, values, 'Scatter X Axis')
787
- populate_default(self.scatter_y_axis, values, 'Scatter Y Axis')
788
- populate_default(self.color_by, values, 'Color by')
789
- populate_default(self.color_scheme, ['Viridis256', 'Magma256', 'Greys256', 'Turbo256'], 'Color by',
790
- default='Viridis256')
791
- populate_default(self.binning_x_axis, values_integral, 'Binning X Axis')
792
- populate_default(self.label_with, values, 'Label with')
793
- populate_default(self.binning_selection_integral, [], 'Binning selection')
794
- populate_default(self.binning_selection_named, [], 'Binning selection')
795
-
796
- default_icon = safe_lookup(options.config, name, 'default', 'Display with', default='None')
797
- icon_values = [v for v, t in data_types.items() if 'BLOB_IMAGE' in t] + ['Icon', 'Dot']
798
- if default_icon != 'None':
799
- if default_icon in icon_values:
800
- del icon_values[icon_values.index(default_icon)]
801
- icon_values.insert(0, default_icon)
802
- if self.icon.value == '':
803
- self.icon.value = icon_values[0]
804
-
805
- self.icon.options = icon_values
806
-
807
- def update_data(self, options, name, data, data_types, type_categories):
808
- self.last_data = data
809
- self.last_data_types = data_types
810
- self.last_type_categories = type_categories
811
- self._update()
812
-
813
-
814
- def process_data_samples(options, name, role, data, types, type_categories):
815
- tabs = []
816
- if options.data_samples.display_tabular:
817
- panel = PanelDataSamplesTabular(options, name, data, types, type_categories)
818
- tabs.append(panel)
819
-
820
- if options.data_samples.display_scatter and options.embedded:
821
- # here we require some python logic, so we need to have a bokeh
822
- # server running to y_axis this view
823
- panel = PanelDataSamplesScatter(options, name, data, types, type_categories)
824
- tabs.append(panel)
825
-
826
- return tabs
827
-
828
-
829
- def process_data_tabular(options, name, role, data, types, type_categories):
830
- tabs = []
831
- panel = PanelDataSamplesTabular(options, name, data, types, type_categories, title=name)
832
- tabs.append(panel)
833
- return tabs
834
-