/
diffusion.py
1544 lines (1155 loc) · 57.3 KB
/
diffusion.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
"""
Module to define interface, workflow and CLI for the review of diffusion MRI data.
"""
import argparse
import asyncio
import sys
import textwrap
import time
import warnings
from abc import ABC
from os.path import basename, join as pjoin, exists as pexists
from textwrap import wrap
import nibabel as nib
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import CheckButtons, RadioButtons
from mrivis.utils import crop_image
from visualqc import config as cfg
from visualqc.image_utils import dwi_overlay_edges
from visualqc.readers import diffusion_traverse_bids
from visualqc.t1_mri import BaseReviewInterface
from visualqc.utils import (check_bids_dir, check_finite_int, check_image_is_4d,
check_out_dir, check_outlier_params, check_time,
check_views, get_axis, pick_slices, scale_0to1,
set_fig_window_title, check_screenshot_params,
remove_matplotlib_axes)
from visualqc.workflows import BaseWorkflowVisualQC
def _prettify(filename, max_width=18):
"""Returns a easily displayable and readable multiline string"""
parts = [s.replace('-', ' ') for s in filename.split('_')]
fixed_width = list()
for p in parts:
if len(p) > max_width:
# indenting by two spaace
fixed_width.extend([' -' + s for s in wrap(p, max_width - 2)])
else:
fixed_width.append(p)
return '\n'.join(fixed_width)
class DiffusionMRIInterface(BaseReviewInterface):
"""Interface for the review of fMRI images."""
def __init__(self,
fig,
axes,
issue_list=cfg.diffusion_mri_default_issue_list,
next_button_callback=None,
quit_button_callback=None,
right_arrow_callback=None,
left_arrow_callback=None,
zoom_in_callback=None,
zoom_out_callback=None,
right_click_callback=None,
show_stdev_callback=None,
scroll_callback=None,
alignment_callback=None,
show_b0_vol_callback=None,
flip_first_last_callback=None,
stop_animation_callback=None,
axes_to_zoom=None,
total_num_layers=5):
"""Constructor"""
super().__init__(fig, axes, next_button_callback, quit_button_callback)
self.issue_list = issue_list
self.prev_axis = None
self.prev_ax_pos = None
self.prev_ax_zorder = None
self.prev_visible = False
self.zoomed_in = False
self.nested_zoomed_in = False
self.total_num_layers = total_num_layers
self.axes_to_zoom = axes_to_zoom
self.next_button_callback = next_button_callback
self.quit_button_callback = quit_button_callback
self.zoom_in_callback = zoom_in_callback
self.zoom_out_callback = zoom_out_callback
self.right_arrow_callback = right_arrow_callback
self.left_arrow_callback = left_arrow_callback
self.scroll_callback = scroll_callback,
self.right_click_callback = right_click_callback
self.show_stdev_callback = show_stdev_callback
self.alignment_callback = alignment_callback
self.flip_first_last_callback = flip_first_last_callback
self.show_b0_vol_callback = show_b0_vol_callback
self.stop_animation_callback = stop_animation_callback
self.add_checkboxes()
self.add_radio_buttons_comparison_method()
self.unzoomable_axes = [self.checkbox.ax, self.radio_bt_vis_type.ax,
self.text_box.ax, self.bt_next.ax, self.bt_quit.ax,
None]
def add_checkboxes(self):
"""
Checkboxes offer the ability to select multiple tags such as Motion,
Ghosting, Aliasing etc, instead of one from a list of mutual exclusive
rating options (such as Good, Bad, Error etc).
"""
ax_checkbox = plt.axes(cfg.position_rating_checkbox_diffusion,
facecolor=cfg.color_rating_axis)
# initially de-activating all
actives = [False] * len(self.issue_list)
self.checkbox = CheckButtons(ax_checkbox, labels=self.issue_list,
actives=actives)
self.checkbox.on_clicked(self.save_issues)
for txt_lbl in self.checkbox.labels:
txt_lbl.set(**cfg.checkbox_font_properties)
for rect in self.checkbox.rectangles:
rect.set_width(cfg.checkbox_rect_width_diffusion)
rect.set_height(cfg.checkbox_rect_height_diffusion)
# lines is a list of n crosses, each cross (x) defined by a tuple of lines
for x_line1, x_line2 in self.checkbox.lines:
x_line1.set_color(cfg.checkbox_cross_color)
x_line2.set_color(cfg.checkbox_cross_color)
self._index_pass = self.issue_list.index(cfg.diffusion_mri_pass_indicator)
def add_radio_buttons_comparison_method(self):
ax_radio = plt.axes(cfg.position_alignment_method_diffusion,
facecolor=cfg.color_rating_axis)
self.radio_bt_vis_type = RadioButtons(ax_radio,
cfg.choices_alignment_comparison_diffusion,
active=0, activecolor='orange')
for lbl in self.radio_bt_vis_type.labels:
lbl.set_fontsize(cfg.fontsize_radio_button_align_method_diffusion)
self.radio_bt_vis_type.on_clicked(self.alignment_callback)
for txt_lbl in self.radio_bt_vis_type.labels:
txt_lbl.set(color=cfg.text_option_color, fontweight='normal')
for circ in self.radio_bt_vis_type.circles:
circ.set(radius=0.06)
def add_process_options(self):
"""redefining it to void its actions intended for T1w MRI interface"""
pass
def maximize_axis(self, ax):
"""zooms a given axis"""
if not self.nested_zoomed_in:
self.prev_ax_pos = ax.get_position()
self.prev_ax_zorder = ax.get_zorder()
self.prev_ax_alpha = ax.get_alpha()
ax.set_position(cfg.zoomed_position_level2)
ax.set_zorder(self.total_num_layers + 1) # bring forth
ax.patch.set_alpha(1.0) # opaque
self.nested_zoomed_in = True
self.prev_axis = ax
def restore_axis(self):
if self.nested_zoomed_in:
self.prev_axis.set(position=self.prev_ax_pos,
zorder=self.prev_ax_zorder,
alpha=self.prev_ax_alpha)
self.nested_zoomed_in = False
def on_mouse(self, event):
"""Callback for mouse events."""
# if event occurs in non-data areas (or axis is None), do nothing
if event.inaxes in self.unzoomable_axes:
return
# any mouse event in data-area stops the current animation
self.stop_animation_callback()
if self.zoomed_in:
# include all the non-data axes here (so they wont be zoomed-in)
if event.inaxes not in self.unzoomable_axes:
if event.dblclick or event.button in [3]:
if event.inaxes in self.axes_to_zoom:
self.maximize_axis(event.inaxes)
else:
self.zoom_out_callback(event)
else:
if self.nested_zoomed_in:
self.restore_axis()
else:
self.zoom_out_callback(event)
elif event.button in [3]:
self.right_click_callback(event)
elif event.dblclick:
self.zoom_in_callback(event)
else:
pass
# redraw the figure - important
self.fig.canvas.draw_idle()
def on_keyboard(self, key_in):
"""Callback to handle keyboard shortcuts to rate and advance."""
# ignore keyboard key_in when mouse within Notes textbox
if key_in.inaxes == self.text_box.ax or key_in.key is None:
return
key_pressed = key_in.key.lower()
# print(key_pressed)
if key_pressed in ['right', 'up']:
self.right_arrow_callback()
elif key_pressed in ['left', 'down']:
self.left_arrow_callback()
elif key_pressed in [' ', 'space']:
# space button stops the current animation
self.stop_animation_callback()
elif key_pressed in ['ctrl+q', 'q+ctrl']:
self.quit_button_callback()
elif key_pressed in ['alt+s', 's+alt']:
self.show_stdev_callback()
elif key_pressed in ['alt+0', '0+alt']:
self.show_b0_vol_callback()
elif key_pressed in ['alt+n', 'n+alt']:
self.flip_first_last_callback()
else:
if key_pressed in cfg.abbreviation_diffusion_mri_default_issue_list:
checked_label = cfg.abbreviation_diffusion_mri_default_issue_list[
key_pressed]
# TODO if user chooses a different set of names, keyboard
# shortcuts might not work
self.checkbox.set_active(self.issue_list.index(checked_label))
else:
pass
self.fig.canvas.draw_idle()
def on_scroll(self, scroll_event):
"""Implements the scroll callback"""
self.scroll_callback(scroll_event)
def get_ratings(self):
"""Returns the final set of checked ratings"""
cbox_statuses = self.checkbox.get_status()
user_ratings = [self.checkbox.labels[idx].get_text()
for idx, this_cbox_active in
enumerate(cbox_statuses) if this_cbox_active]
return user_ratings
def allowed_to_advance(self):
"""
Method to ensure work is done for current iteration,
before allowing the user to advance to next subject.
Returns False if atleast one of the following conditions are not met:
Atleast Checkbox is checked
"""
return self._is_checkbox_ticked(self.checkbox)
def save_issues(self, label):
"""
Update the rating
This function is called whenever set_active() happens on any label,
if checkbox.eventson is True.
"""
if label == cfg.visual_qc_pass_indicator:
self.clear_checkboxes(except_pass=True)
else:
self.clear_pass_only_if_on()
self.fig.canvas.draw_idle()
def clear_checkboxes(self, except_pass=False):
"""Clears all checkboxes.
if except_pass=True,
does not clear checkbox corresponding to cfg.t1_mri_pass_indicator
"""
cbox_statuses = self.checkbox.get_status()
for index, this_cbox_active in enumerate(cbox_statuses):
if except_pass and index == self._index_pass:
continue
# if it was selected already, toggle it.
if this_cbox_active:
# not calling checkbox.set_active() as it calls the callback
# self.save_issues() each time, if eventson is True
self._toggle_visibility_checkbox(index)
def clear_pass_only_if_on(self):
"""Clear pass checkbox only"""
cbox_statuses = self.checkbox.get_status()
if cbox_statuses[self._index_pass]:
self._toggle_visibility_checkbox(self._index_pass)
def _toggle_visibility_checkbox(self, index):
"""toggles the visibility of a given checkbox"""
l1, l2 = self.checkbox.lines[index]
l1.set_visible(not l1.get_visible())
l2.set_visible(not l2.get_visible())
def reset_figure(self):
"""Resets the figure to prepare it for display of next subject."""
self.zoom_out_callback(None)
self.restore_axis()
self.clear_data()
self.clear_checkboxes()
self.clear_notes_annot()
def remove_UI_local(self):
"""Removes module specific UI elements for cleaner screenshots"""
remove_matplotlib_axes([self.checkbox, self.radio_bt_vis_type])
class DiffusionRatingWorkflow(BaseWorkflowVisualQC, ABC):
"""
Rating workflow for BOLD fMRI.
"""
def __init__(self,
in_dir,
out_dir,
apply_preproc=False,
id_list=None,
name_pattern=None,
images_for_id=None,
delay_in_animation=cfg.delay_in_animation_diffusion_mri,
issue_list=cfg.diffusion_mri_default_issue_list,
in_dir_type='BIDS',
outlier_method=cfg.default_outlier_detection_method,
outlier_fraction=cfg.default_outlier_fraction,
outlier_feat_types=cfg.diffusion_mri_features_OLD,
disable_outlier_detection=True,
prepare_first=False,
vis_type=None,
views=cfg.default_views_diffusion,
num_slices_per_view=cfg.default_num_slices_diffusion,
num_rows_per_view=cfg.default_num_rows_diffusion,
screenshot_only=cfg.default_screenshot_only):
"""
Constructor.
"""
if id_list is None and 'BIDS' in in_dir_type:
id_list = pjoin(in_dir, 'participants.tsv')
super().__init__(id_list, in_dir, out_dir,
outlier_method, outlier_fraction,
outlier_feat_types, disable_outlier_detection,
screenshot_only=screenshot_only)
# basic cleaning before display
# whether to remove and detrend before making carpet plot
self.apply_preproc = apply_preproc
self.vis_type = vis_type
self.issue_list = issue_list
self.in_dir_type = in_dir_type
self.name_pattern = name_pattern
self.images_for_id = images_for_id
self.expt_id = 'rate_diffusion'
self.suffix = self.expt_id
self.current_alert_msg = None
self.prepare_first = prepare_first
#
self.current_grad_index = 0
self.delay_in_animation = delay_in_animation
self.checking_alignment = False # reflects default data viz radio btn
self.init_layout(views, num_rows_per_view, num_slices_per_view)
self.init_getters()
self.__module_type__ = 'diffusion'
def preprocess(self):
"""
Preprocess the input data
e.g. compute features, make complex visualizations etc.
before starting the review process.
"""
if not self.disable_outlier_detection:
print('Preprocessing data - please wait .. '
'\n\t(or contemplate the vastness of universe! )')
self.extract_features()
self.detect_outliers()
# no complex vis to generate - skipping
def prepare_UI(self):
"""Main method to run the entire workflow"""
self.open_figure()
self.add_UI()
self.add_histogram_panel()
def init_layout(self, views, num_rows_per_view,
num_slices_per_view, padding=cfg.default_padding):
self.views = views
self.num_slices_per_view = num_slices_per_view
self.num_rows_per_view = num_rows_per_view
self.num_rows = len(self.views) * self.num_rows_per_view
self.num_cols = int(
(len(self.views) * self.num_slices_per_view) / self.num_rows)
self.padding = padding
def init_getters(self):
"""Initializes the getters methods for input paths and feature readers."""
from visualqc.features import diffusion_mri_features
self.feature_extractor = diffusion_mri_features
if 'BIDS' in self.in_dir_type.upper():
from visualqc.utils import process_bids_dir
self.units, self.unit_by_id, self.id_list = process_bids_dir(
self.in_dir, diffusion_traverse_bids)
else:
raise NotImplementedError('Only the BIDS format is supported for now!')
def open_figure(self):
"""Creates the master figure to show everything in."""
# number of stats to be overlaid on top of carpet plot
self.num_stats = 3
self.figsize = cfg.default_review_figsize
# empty/dummy data for placeholding
empty_image = np.full((200, 200), 0.0)
label_x, label_y = (5, 5) # x, y in image data space
empty_vec = np.full((200, 1), 0.0)
gradients = list(range(200))
# overlay order -- larger appears on top of smaller
self.layer_order_carpet = 1
self.layer_order_stats = 2
self.layer_order_zoomedin = 3
self.layer_order_to_hide = -1
self.total_num_layers = 3
plt.style.use('dark_background')
# 1. main carpet, in the background
self.fig, self.ax_carpet = plt.subplots(1, 1, figsize=self.figsize)
set_fig_window_title(
self.fig, f'VisualQC Diffusion MRI : {self.in_dir} ')
self.ax_carpet.set_zorder(self.layer_order_carpet)
# vmin/vmax are controlled, because we rescale all to [0, 1]
self.imshow_params_carpet = dict(interpolation='none', aspect='auto',
origin='lower', cmap='gray', vmin=0.0,
vmax=1.0)
self.ax_carpet.yaxis.set_visible(False)
self.ax_carpet.set_xlabel('gradient')
self.carpet_handle = self.ax_carpet.imshow(empty_image,
**self.imshow_params_carpet)
self.ax_carpet.set_frame_on(False)
self.ax_carpet.set_ylim(auto=True)
# 2. temporal traces of image stats
tmp_mat = self.fig.subplots(self.num_stats, 1, sharex=True)
self.stats_axes = tmp_mat.flatten()
self.stats_handles = [None] * len(self.stats_axes)
stats = [(empty_vec, 'mean signal', 'cyan'),
(empty_vec, 'std. dev signal', 'xkcd:orange red'),
(empty_vec, 'DVARS', 'xkcd:mustard')]
for ix, (ax, (stat, label, color)) in enumerate(zip(self.stats_axes, stats)):
(vh,) = ax.plot(gradients, stat, color=color)
self.stats_handles[ix] = vh
vh.set_linewidth(cfg.linewidth_stats_diffusion)
vh.set_linestyle(cfg.linestyle_stats_diffusion)
ax.xaxis.set_visible(False)
ax.set_frame_on(False)
ax.set_ylim(auto=True)
ax.set_ylabel(label, color=color)
ax.set_zorder(self.layer_order_stats)
ax.set_alpha(cfg.alpha_stats_overlay)
ax.tick_params(color=color, labelcolor=color)
ax.spines['left'].set_color(color)
ax.spines['left'].set_position(('outward', 1))
# sharing the time point axis
self.stats_axes[0].get_shared_x_axes().join(self.ax_carpet.xaxis,
self.stats_axes[0].xaxis)
# self.stats_axes[0].autoscale()
# 3. axes to show slices in foreground when a time point is selected
matrix_handles = self.fig.subplots(self.num_rows, self.num_cols,
subplot_kw=dict(rasterized=True),
gridspec_kw=dict(wspace=0.01,
hspace=0.01))
self.fg_axes = matrix_handles.flatten()
# vmin/vmax are controlled, because we rescale all to [0, 1]
self.imshow_params_zoomed = dict(interpolation='none', aspect='equal',
rasterized=True, origin='lower',
cmap='gray',
vmin=0.0, vmax=1.0)
# images to be shown in the forground
self.images_fg = [None] * len(self.fg_axes)
self.images_fg_label = [None] * len(self.fg_axes)
for ix, ax in enumerate(self.fg_axes):
ax.axis('off')
self.images_fg[ix] = ax.imshow(empty_image, **self.imshow_params_zoomed)
self.images_fg_label[ix] = ax.text(label_x, label_y, '',
**cfg.slice_num_label_properties,
zorder=self.layer_order_zoomedin + 1)
ax.set(visible=False, zorder=self.layer_order_zoomedin)
self.foreground_h = self.fig.text(cfg.position_zoomed_gradient[0],
cfg.position_zoomed_gradient[1],
' ', **cfg.annot_gradient)
self.foreground_h.set_visible(False)
# identifying axes that could be hidden to avoid confusion
self.background_artists = list(self.stats_axes) + [self.ax_carpet, ]
self.foreground_artists = list(self.fg_axes) + [self.foreground_h, ]
# separating the list below to allow for differing x axes, while being
# background
self.axes_common_xaxis = list(self.stats_axes) + [self.ax_carpet, ]
# leaving some space on the right for review elements
plt.subplots_adjust(**cfg.review_area)
def add_UI(self):
"""Adds the review UI with defaults"""
self.UI = DiffusionMRIInterface(self.fig, self.ax_carpet, self.issue_list,
next_button_callback=self.next,
quit_button_callback=self.quit,
right_click_callback=self.zoom_in_on_gradient,
right_arrow_callback=self.show_next,
left_arrow_callback=self.show_prev,
scroll_callback=self.change_gradient_by_step,
zoom_in_callback=self.zoom_in_on_gradient,
zoom_out_callback=self.zoom_out_callback,
show_stdev_callback=self.show_stdev,
show_b0_vol_callback=self.show_b0_gradient,
flip_first_last_callback=self.flip_first_last,
alignment_callback=self.alignment_check,
stop_animation_callback=self.stop_animation,
axes_to_zoom=self.fg_axes,
total_num_layers=self.total_num_layers)
# connecting callbacks
self.con_id_click = self.fig.canvas.mpl_connect('button_press_event',
self.UI.on_mouse)
self.con_id_keybd = self.fig.canvas.mpl_connect('key_press_event',
self.UI.on_keyboard)
self.con_id_scroll = self.fig.canvas.mpl_connect('scroll_event',
self.UI.on_scroll)
self.fig.set_size_inches(self.figsize)
def add_histogram_panel(self):
"""Extra axis for histogram"""
pass
def update_histogram(self, img):
"""
Updates histogram with current image data.
Mimic behaviour in T1 mri workflow if helpful!
"""
pass
def update_alerts(self):
"""Keeps a box, initially invisible."""
if self.current_alert_msg is not None:
h_alert_text = self.fig.text(cfg.position_outlier_alert[0],
cfg.position_outlier_alert[1],
self.current_alert_msg,
**cfg.alert_text_props)
# adding it to list of elements to cleared when advancing to next subject
self.UI.data_handles.append(h_alert_text)
def add_alerts(self):
"""Brings up an alert if subject id is detected to be an outlier."""
flagged_as_outlier = self.current_unit_id in self.by_sample
if flagged_as_outlier:
alerts_list = self.by_sample.get(self.current_unit_id,
None) # None, if id not in dict
print('\n\tFlagged as a possible outlier by these measures:'
'\n\t\t{}'.format('\t'.join(alerts_list)))
strings_to_show = ['Flagged as an outlier:', ] + alerts_list
self.current_alert_msg = '\n'.join(strings_to_show)
self.update_alerts()
else:
self.current_alert_msg = None
def load_unit(self, unit_id):
"""Loads the image data for display."""
img_path = self.unit_by_id[unit_id]['image']
bval_path = self.unit_by_id[unit_id]['bval']
try:
hdr = nib.load(img_path)
self.hdr_this_unit = nib.as_closest_canonical(hdr)
self.img_this_unit_raw = self.hdr_this_unit.get_fdata()
num_dwi_volumes = self.img_this_unit_raw.shape[-1]
if (not pexists(bval_path)) or (bval_path.lower() == 'assume_first'):
self.b_values_this_unit = None # to indicate we have no info
self.b0_indices = [False, ]*num_dwi_volumes
self.b0_indices[0] = True # assume first volume is b=0
# do the opposite with dw volumes
self.dw_indices = [True, ] * num_dwi_volumes
self.dw_indices[0] = False
self.b0_indices = np.flatnonzero(self.b0_indices)
self.dw_indices = np.flatnonzero(self.dw_indices)
else:
self.b_values_this_unit = np.loadtxt(bval_path).flatten()
self.b0_indices = np.flatnonzero(self.b_values_this_unit == 0)
self.dw_indices = np.flatnonzero(self.b_values_this_unit != 0)
except Exception as exc:
print(exc)
print('Unable to read image at \n\t{}'.format(img_path))
skip_subject = True
else:
check_image_is_4d(self.img_this_unit_raw)
if len(self.b0_indices) < 1:
skip_subject = True
print('There are no b=0 volumes for {}! '
'Skipping it..'.format(unit_id))
return skip_subject
if len(self.b0_indices) == 1:
self.b0_volume = self.img_this_unit_raw[
..., self.b0_indices].squeeze()
else:
# TODO which is the correct b=0 volumes are available
# TODO is there a way to reduce multiple into one
print('Multiple b=0 volumes found for {} '
'- choosing the first!'.format(unit_id))
self.b0_volume = self.img_this_unit_raw[..., self.b0_indices[0]].squeeze()
# need more thorough checks on whether image loaded is indeed DWI
self.dw_volumes = self.img_this_unit_raw[:, :, :, self.dw_indices]
self.num_gradients = self.dw_volumes.shape[3]
# to check alignment
self.current_grad_index = 0
skip_subject = False
if np.count_nonzero(self.img_this_unit_raw) == 0:
skip_subject = True
print('Diffusion image is empty!')
return skip_subject
def display_unit(self):
"""Adds multi-layered composite."""
# TODO show median signal instead of mean - or option for both?
self.stdev_this_unit, self.mean_this_unit = self.stats_over_gradients()
# TODO what about slice timing correction?
# num_voxels = np.prod(self.dw_volumes.shape[0:3])
# TODO better way to label each gradient would be with unit vector/direction
gradients = list(range(self.num_gradients))
# 1. compute necessary stats/composites
carpet, mean_signal_spatial, stdev_signal_spatial, dvars = self.compute_stats()
# 2. display/update the data
self.carpet_handle.set_data(carpet)
self.stats_handles[0].set_data(gradients, mean_signal_spatial)
self.stats_handles[1].set_data(gradients, stdev_signal_spatial)
# not displaying DVARS for t=0, as its always 0
self.stats_handles[2].set_data(gradients[1:], dvars[1:])
# 3. updating axes limits and views
self.update_axes_limits(self.num_gradients, carpet.shape[0])
self.refresh_layer_order()
# clean up
del carpet, mean_signal_spatial, stdev_signal_spatial, dvars
def zoom_in_on_gradient(self, event):
"""Brings up selected time point"""
if event.x is None:
return
# to distinguish between no or alignment overlay
self.checking_alignment = False
# computing x in axes data coordinates myself,
# to avoid overlaps with other axes
# retrieving the latest transform after to ensure its accurate at click time
x_in_carpet, _y = self._event_location_in_axis(event, self.ax_carpet)
# clipping it to [0, T]
self.current_grad_index = max(0, min(self.dw_volumes.shape[3],
int(round(x_in_carpet))))
self.show_gradient()
def change_gradient_by_step(self, step):
"""Changes the index of the gradient being shown.
Step could be negative to move in opposite direction.
"""
# skipping unnecessary computation
new_index = self.current_grad_index + step
if (new_index > self.num_gradients - 1) or (new_index < 0):
return
# clipping from 0 to num_gradients
self.current_grad_index = max(0, min(self.num_gradients, new_index))
self.show_gradient()
def show_b0_gradient(self):
"""Shows the b=0 volume"""
# TODO what if more than one b=0 volumees are available
if (self.current_grad_index == self.b0_indices[0]) and self.UI.zoomed_in:
return # do nothing
self.show_3dimage(self.b0_volume.squeeze(), 'b=0 volume')
def animate_through_gradients(self):
"""Loops through all gradients, in mulitslice view, to help spot artefacts"""
asyncio.run(self._animate_through_gradients())
async def _animate_through_gradients(self):
"""Show image 1, wait, show image 2"""
# fixing the same slices for all gradients
slices = pick_slices(self.b0_volume, self.views, self.num_slices_per_view)
for grad_idx in range(self.num_gradients):
self.show_3dimage(self.dw_volumes[:, :, :, grad_idx].squeeze(),
slices=slices, annot='gradient {}'.format(grad_idx))
plt.pause(cfg.plotting_pause_interval)
def flip_first_last(self):
"""Flips between first and last volume to identify any pulsation artefacts"""
# 0 and -1 are indexing into self.dw_volumes, not b0_volumes
self.flip_between_two(0, -1)
def flip_between_two(self, index_one, index_two, first_index_in_b0=False):
"""Flips between first and last volume to identify any pulsation artefacts"""
asyncio.run(
self._flip_between_two_nTimes(index_one, index_two,
first_index_in_b0=first_index_in_b0))
async def _flip_between_two_nTimes(self, index_one, index_two,
first_index_in_b0=False):
"""Show first, wait, show last, repeat"""
if first_index_in_b0:
_first_vol = self.b0_volume # [:, :, :, index_one].squeeze()
_id_first = 'b=0' # index {}'.format(index_one)
else:
_first_vol = self.dw_volumes[:, :, :, index_one].squeeze()
_id_first = 'DW gradient {}'.format(index_one)
_second_vol = self.dw_volumes[:, :, :, index_two].squeeze()
if index_two < 0:
# -1 would be confusing to the user
index_two = self.num_gradients + index_two
_id_second = 'DW gradient {}'.format(index_two)
for _ in range(cfg.num_times_to_animate_diffusion_mri):
for img, txt in ((_first_vol, _id_first),
(_second_vol, _id_second)):
self.show_3dimage(img, txt)
plt.pause(cfg.plotting_pause_interval)
def alignment_check(self, label=None):
"""Chooses between the type of alignment check to show"""
if label in ['None', None]:
self.zoom_out_callback(event=None)
self.checking_alignment = False
self.current_alignment_check = None
return # nothing to do
else:
self.checking_alignment = True
self.current_alignment_check = label
if label in ['Align to b0 animate', 'Alignment to b0', 'Align to b0',
'Align to b0 edges']:
self.alignment_to_b0()
elif label in ['Animate all', 'Flip through all']:
self.animate_through_gradients()
elif label in ['Flip first & last', ]:
self.flip_first_last()
else:
raise NotImplementedError(f'alignment check:{label} not implemented.')
def alignment_to_b0(self):
"""Overlays a given gradient on b0 volume to check for alignment isses"""
self.checking_alignment = True
if self.current_alignment_check in ['Align to b0 animate',
'Align to b0']:
self.flip_between_two(self.b0_indices, self.current_grad_index,
first_index_in_b0=True)
elif self.current_alignment_check in ['Align to b0 (edges)', ]:
self.overlay_dwi_edges()
def overlay_dwi_edges(self):
# not cropping to help checking align in full FOV
overlaid = scale_0to1(self.b0_volume)
base_img = scale_0to1(self.dw_volumes[..., self.current_grad_index].squeeze())
slices = pick_slices(base_img, self.views, self.num_slices_per_view)
for ax_index, (dim_index, slice_index) in enumerate(slices):
mixed = dwi_overlay_edges(get_axis(base_img, dim_index, slice_index),
get_axis(overlaid, dim_index, slice_index))
self.images_fg[ax_index].set(data=mixed)
self.images_fg_label[ax_index].set_text(str(slice_index))
# this needs to be done outside show_image3d, as we need custom mixing
self._set_backgrounds_visibility(False)
self._set_foregrounds_visibility(True)
self._identify_foreground('Alignment check to b=0, '
'grad index {}'.format(self.current_grad_index))
def stop_animation(self):
pass
def show_next(self):
if self.current_grad_index == self.dw_volumes.shape[3] - 1:
return # do nothing
self.current_grad_index = min(self.dw_volumes.shape[3] - 1,
self.current_grad_index + 1)
if self.checking_alignment:
self.alignment_to_b0()
else:
self.show_gradient()
def show_prev(self):
if self.current_grad_index == 0:
return # do nothing
self.current_grad_index = max(self.current_grad_index - 1, 0)
if self.checking_alignment:
self.alignment_to_b0()
else:
self.show_gradient()
def zoom_out_callback(self, event):
"""Hides the zoomed-in axes (showing frame)."""
self._set_foregrounds_visibility(False)
self._set_backgrounds_visibility(True)
@staticmethod
def _event_location_in_axis(event, axis):
"""returns (x_in_axis, y_in_axis)"""
# display pixels to axis coords
return axis.transData.inverted().transform_point((event.x, event.y))
def show_gradient(self):
"""Exhibits a selected timepoint on top of stats/carpet"""
if (self.current_grad_index < 0) or (self.current_grad_index >= self.num_gradients):
print('Requested time point outside range [0, {}]'
''.format(self.num_gradients))
return
self.show_3dimage(
self.dw_volumes[:, :, :, self.current_grad_index].squeeze(),
'zoomed-in gradient {}'.format(self.current_grad_index))
def show_3dimage(self, image, annot, slices=None):
"""generic display method."""
self.attach_image_to_foreground_axes(image, slices=slices)
self._identify_foreground(annot)
self._set_backgrounds_visibility(False)
self._set_foregrounds_visibility(True)
def _identify_foreground(self, text):
"""show the time point"""
self.foreground_h.set_text(text)
self.foreground_h.set_visible(True)
def _set_backgrounds_visibility(self, visibility=True):
for ax in self.background_artists:
ax.set(visible=visibility)
def _set_foregrounds_visibility(self, visibility=False):
if visibility:
zorder = self.layer_order_zoomedin
else:
zorder = self.layer_order_to_hide
for ax in self.foreground_artists:
ax.set(visible=visibility, zorder=zorder)
# this state flag in important
self.UI.zoomed_in = visibility
def show_stdev(self):
"""Shows the image of temporal std. dev"""
if self.stdev_this_unit is not None:
self.attach_image_to_foreground_axes(self.stdev_this_unit,
cmap=cfg.colormap_stdev_diffusion)
self._identify_foreground('Std. dev over gradients')
self.UI.zoomed_in = True
else:
# if the number of b0 volumes are not sufficient
print('SD for this unit is not available')