-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvisualizer.py
More file actions
4342 lines (3768 loc) · 176 KB
/
visualizer.py
File metadata and controls
4342 lines (3768 loc) · 176 KB
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
#!/usr/bin/env python
# 3D image visualization
# Author: David Young, 2017, 2020
"""3D Visualization GUI.
This module is the main GUI for visualizing 3D objects from imaging stacks.
The module can be run either as a script or loaded and initialized by
calling main().
Examples:
Launch the GUI with the given file at a particular size and offset::
./run.py --img /path/to/file.czi --offset 30,50,205 --size 150,150,10
"""
import glob
import pprint
from collections import OrderedDict
from enum import auto, Enum
import os
import subprocess
import sys
from typing import Dict, List as TypeList, Optional, Sequence, TYPE_CHECKING, \
Tuple, Type, Union
import matplotlib
matplotlib.use("Qt5Agg") # explicitly use PyQt5 for custom GUI events
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib import figure
import numpy as np
from PyQt5 import Qt, QtWidgets, QtCore
# adjust for HiDPI screens before QGuiApplication is created, necessary
# on Windows and Linux (not needed but no apparent affect on MacOS)
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
try:
# use policy introduced in Qt 5.14 to account for non-integer factor
# scaling, eg 150%, which avoids excessive window size upscaling
QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy(
QtCore.Qt.HighDpiScaleFactorRoundingPolicy.RoundPreferFloor)
except AttributeError:
pass
# import PyFace components after HiDPI adjustment
try:
# WORKAROUND: Mayavi as of v4.8.1 uses the older qt4 instead of qt
from traits.etsconfig.api import ETSConfig
ETSConfig.toolkit = "qt4"
except AttributeError:
print("Could not set Traits ETSConfig")
pass
from pyface import confirmation_dialog
from pyface.api import DirectoryDialog, FileDialog, OK, YES, CANCEL
from pyface.image_resource import ImageResource
from traits.api import Any, Array, Bool, Button, Event, Float, Instance, \
Int, List, observe, on_trait_change, Property, push_exception_handler, \
Str, HasTraits
from traitsui.api import ArrayEditor, BooleanEditor, CheckListEditor, \
EnumEditor, HGroup, HSplit, Item, NullEditor, ProgressEditor, RangeEditor, \
StatusItem, TextEditor, VGroup, View, Tabbed, TabularEditor
from traitsui.basic_editor_factory import BasicEditorFactory
try:
from traitsui.qt.editor import Editor
except ModuleNotFoundError:
from traitsui.qt4.editor import Editor
from traitsui.tabular_adapter import TabularAdapter
try:
from tvtk.pyface.scene_editor import SceneEditor
from tvtk.pyface.scene_model import SceneModelError
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core.ui.mayavi_scene import MayaviScene
import vtk
except ImportError:
SceneEditor = None
SceneModelError = None
MlabSceneModel = None
MayaviScene = None
vtk = None
from magmap.atlas import ontology
from magmap.brain_globe import bg_controller
from magmap.cv import classifier, colocalizer, cv_nd, detector, segmenter, \
verifier
from magmap.gui import atlas_editor, atlas_threads, import_threads, \
plot_editor, roi_editor, verifier_editor, vis_3d, vis_handler
from magmap.io import cli, importer, libmag, load_env, naming, np_io, sitk_io, \
sqlite
from magmap.plot import colormaps, plot_2d, plot_3d
from magmap.settings import config, prefs_prof, profiles
if TYPE_CHECKING:
try:
from brainglobe_atlasapi import BrainGlobeAtlas
except ImportError:
from bg_atlasapi import BrainGlobeAtlas
from matplotlib import colors as mpl_colors
from magmap.plot import plot_support
# logging instance
_logger = config.logger.getChild(__name__)
def main():
"""Starts the visualization GUI.
Also sets up exception handling.
"""
# show complete stacktraces for debugging
push_exception_handler(reraise_exceptions=True)
if vtk is not None:
# suppress output window on Windows but print errors to console
vtk_out = vtk.vtkOutputWindow()
vtk_out.SetInstance(vtk_out)
# create Trait-enabled GUI
visualization = Visualization(config.img5d)
visualization.configure_traits()
class _MPLFigureEditor(Editor):
"""Custom TraitsUI editor to handle Matplotlib figures."""
scrollable = True
def init(self, parent):
self.control = self._create_canvas(parent)
self.set_tooltip()
def update_editor(self):
pass
def _create_canvas(self, parent):
"""Create canvas through the Matplotlib Qt backend."""
mpl_canvas = FigureCanvasQTAgg(self.value)
return mpl_canvas
class MPLFigureEditor(BasicEditorFactory):
"""Custom TraitsUI editor for a Matplotlib figure."""
klass = _MPLFigureEditor
class SegmentsArrayAdapter(TabularAdapter):
"""Blobs TraitsUI table adapter."""
columns = [("i", "index"), ("z", 0), ("row", 1), ("col", 2),
("radius", 3), ("confirmed", 4), ("channel", 6), ("abs_z", 7),
("abs_y", 8), ("abs_x", 9)]
index_text = Property
def _get_index_text(self):
return str(self.row)
class ProfileCats(Enum):
"""Profile categories enumeration."""
ROI = "ROI profiles"
ATLAS = "Atlas profiles"
GRID = "Grid Search"
class TraitsList(HasTraits):
"""Generic Traits-enabled list."""
selections = List([""])
class ProfilesArrayAdapter(TabularAdapter):
"""Profiles TraitsUI table adapter."""
columns = [("Category", 0), ("Profile", 1), ("Channel", 2)]
widths = {0: 0.3, 1: 0.6, 2: 0.1}
def get_width(self, object, trait, column):
"""Specify column widths."""
return self.widths[column]
class ImportFilesArrayAdapter(TabularAdapter):
"""Import files TraitsUI table adapter."""
columns = [("File", 0), ("Channel", 1)]
widths = {0: 0.9, 1: 0.1}
def get_width(self, object, trait, column):
"""Specify column widths."""
return self.widths[column]
class ImportModes(Enum):
"""Enumerations for import modes."""
DIR = auto()
MULTIPAGE = auto()
class Styles2D(Enum):
"""Enumerations for 2D ROI GUI styles."""
SQUARE = "Square layout"
SQUARE_3D = "Square with 3D"
SINGLE_ROW = "Single row"
WIDE = "Wide region"
ZOOM3 = "3 level zoom"
ZOOM4 = "4 level zoom"
THIN_ROWS = "Thin rows"
class RegionOptions(Enum):
"""Enumerations for region options."""
BOTH_SIDES = "Both sides"
INCL_CHILDREN = "Children"
APPEND = "Append"
SHOW_ALL = "Show all"
class AtlasEditorOptions(Enum):
"""Enumerations for Atlas Editor options."""
SHOW_LABELS = "Labels"
SYNC_ROI = "Sync ROI"
ZOOM_ROI = "Zoom ROI"
CROSSHAIRS = "Crosshairs"
class Vis3dOptions(Enum):
"""Enumerations for 3D viewer options."""
RAW = "Raw"
SURFACE = "Surface"
CLEAR = "Clear"
PANES = "Panes"
SHADOWS = "Shadows"
class BlobsVisibilityOptions(Enum):
"""Enumerations for blob visibility options."""
VISIBLE = "Visible"
class ColocalizeOptions(Enum):
"""Enumerations for co-localization options."""
DEFAULT = ""
INTENSITY = "Intensity"
MATCHES = "Matches"
class BlobColorStyles(Enum):
"""Enumerations for blob color style options."""
ATLAS_LABELS = "Atlas label colors"
UNIQUE = "Unique colors"
CHANNEL = "Channel colors"
class ControlsTabs(Enum):
"""Enumerations for controls tabs."""
ROI = auto()
DETECT = auto()
PROFILES = auto()
ADJUST = auto()
IMPORT = auto()
class BrainGlobeArrayAdapter(TabularAdapter):
"""Import files TraitsUI table adapter."""
columns = [("Atlas", 0), ("Ver", 1), ("Installed?", 2)]
widths = {0: 0.5, 1: 0.1, 2: 0.4}
def get_width(self, object, trait, column):
"""Specify column widths."""
return self.widths[column]
class Visualization(HasTraits):
"""GUI for choosing a region of interest and segmenting it.
TraitUI-based graphical interface for selecting dimensions of an
image to view and segment.
Attributes:
x_low, x_high, ... (Int): Low and high values for image coordinates.
x_offset: Integer trait for x-offset.
y_offset: Integer trait for y-offset.
z_offset: Integer trait for z-offset.
scene: The main scene
btn_redraw: Button editor for drawing the reiong of
interest.
btn_detect: Button editor for segmenting the ROI.
roi: The ROI.
segments: Array of segments; if None, defaults to a Numpy array
of zeros with one row.
segs_selected: List of indices of selected segments.
controls_created (Bool): True if the controls have been created;
defaults to False.
mpl_fig_active (Any): The Matplotlib figure currently shown.
scene_3d_shown (bool): True if the Mayavi 3D plot has been shown.
selected_viewer_tab (Enum): The Enum corresponding to the selected
tab in the viewer panel.
select_controls_tab (int): Enum value from :class:`ControlsTabs` to
select the controls panel tab.
stale_viewers (
dict[:class:`magmap.gui.vis_handler.vis_handler.ViewerTabs`,
:class:`magmap.gui.vis_handler.vis_handler.StaleFlags`]):
Dictionary of viewer tab Enums to stale flag Enums, where the
flag indicates the update that the viewer would require.
Defaults to all viewers set to
:class:`vis_handler.StaleFlags.IMAGE`.
"""
#: default ROI name.
_ROI_DEFAULT: str = "None selected"
# File selection
_filename = Str(
tooltip="Load an image. If the file format requires import, the\n"
"Import tab will open automatically.")
_filename_btn = Button("Browse")
_channel_names = Instance(TraitsList)
_channel = List # selected channels, 0-based
_rgb = Bool(config.rgb, tooltip="Show image as RGB(A)")
_rgb_enabled = Bool
_merge_chls = Bool(
tooltip="Merge channels using additive blending"
)
# main registered image available and selected dropdowns
_main_img_name_avail = Str
_main_img_names_avail = Instance(TraitsList)
_MAIN_IMG_NAME_AVAIL_DEFAULT = "Available ({})"
_main_img_name = Str
_main_img_names = Instance(TraitsList)
_MAIN_IMG_NAME_DEFAULT = "Selected ({})"
# labels registered image selection dropdown
_labels_img_name = Str
_labels_img_names = Instance(TraitsList)
_labels_ref_path = Str # labels ontology reference path
_labels_ref_btn = Button("Browse") # button to select ref file
_reload_btn = Button("Reload") # button to reload images
# ROI selection
# image coordinate limits
x_low = Int(0)
x_high = Int(100)
y_low = Int(0)
y_high = Int(100)
z_low = Int(0)
z_high = Int(100)
# ROI offset and shape
x_offset = Int
y_offset = Int
z_offset = Int
roi_array = Array(Int, shape=(1, 3), editor=ArrayEditor(format_str="%0d"))
_roi_center = Bool(tooltip="Treat the offset as the center of the ROI")
btn_redraw = Button("Redraw")
_btn_save_fig = Button("Save Figure")
_roi_btn_help = Button("Help")
roi = None # combine with roi_array?
_rois_selections = Instance(TraitsList)
rois_check_list = Str
_rois_dict = None
_rois = None
_roi_feedback = Str()
# Detect panel
btn_detect = Button("Detect")
btn_save_segments = Button("Save Blobs")
_btn_verifier = Button(
"Open Verifier",
tooltip="Open a viewer displaying each blob in a separate plot to\n"
"verify classifications.")
_segs_chls_names = Instance(TraitsList) # blob detection channels
_segs_chls = List # selected channels, 0-based
_segs_labels = List( # blob label selector
["-1"],
tooltip="All blob labels will be set to this value when running Detect",
)
_segs_model_path = Str # blobs classifier model path
_segs_model_btn = Button("Browse") # button to select model file
_segs_visible = List # blob visibility options
_colocalize = List # blob co-localization options
_blob_color_style = List # blob coloring
_segments = Array # table of blobs
_segs_moved = [] # orig seg of moved blobs to track for deletion
_scale_detections_low = Float(0)
_scale_detections_high = Float # needs to be trait to dynamically update
scale_detections = Float(
tooltip="Change the size of blobs in the 3D viewer"
)
# for blob mask slider
_segs_mask_low = 1
_segs_mask_high = Int(1)
_segs_mask = Int(
1, tooltip="Change the fraction of blobs shown in the 3D viewer"
)
segs_selected = List # indices
_segs_row_scroll = Int() # row index to scroll the table
# multi-select to allow updating with a list, but segment updater keeps
# selections to single when updating them
_segs_refresh_evt = Event()
segs_table = TabularEditor(
adapter=SegmentsArrayAdapter(), multi_select=True,
selected_row="segs_selected", scroll_to_row="_segs_row_scroll",
refresh="_segs_refresh_evt")
segs_in_mask = None # boolean mask for segments in the ROI
segs_cmap = None
segs_feedback = Str("Segments output")
labels = None # segmentation labels
# Profiles panel
_profiles_cats = List
_profiles_names = Instance(TraitsList)
_profiles_name = Str
_profiles_chls = List(
tooltip="Channels to apply the selected profile"
)
_profiles_table = TabularEditor(
adapter=ProfilesArrayAdapter(), editable=True, auto_resize_rows=True,
stretch_last_section=False, drag_move=True)
_profiles = List # profiles table list
_profiles_add_btn = Button(
"Add",
tooltip="Click to add the selected profile for the checked channels.\n"
"Press Backspace/Delete key to remove the selected table row.\n"
"Drag rows to rearrange the order of loaded profiles."
)
_profiles_load_btn = Button(
"Rescan",
tooltip="Rescan the 'profiles' folder for YAML files"
)
_profiles_preview = Str # preview the selected profile
_profiles_combined = Str # combined profiles for selected category
_profiles_ver = Str
_profiles_reset_prefs_btn = Button("Reset preferences")
_profiles_btn_help = Button("Help")
_profiles_reset_prefs = Bool # trigger resetting prefs in handler
# Image adjustment panel
_imgadj_names = Instance(TraitsList)
_imgadj_name = Str
_imgadj_chls_names = Instance(TraitsList)
_imgadj_chls = Str
_imgadj_color_name = Str(
tooltip="Colormap for the channel. Start typing to search.")
_imgadj_color_names = Instance(TraitsList)
_imgadj_min = Float
_imgadj_min_low = Float(0) # must have val in Python >= 3.10
_imgadj_min_high = Float(1) # must have val > min in Python >= 3.12
_imgadj_min_auto = Bool
_imgadj_max = Float
_imgadj_max_low = Float(0)
_imgadj_max_high = Float(1)
_imgadj_max_auto = Bool
_imgadj_brightness = Float
_imgadj_brightness_low = Float(0)
_imgadj_brightness_high = Float(1)
_imgadj_contrast = Float
_imgadj_alpha = Float
_imgadj_alpha_blend = Float(0.5)
_imgadj_alpha_blend_check = Bool(
tooltip="Blend the overlapping parts of imags to shown alignment.\n"
"Applied to the first two channels of the main image."
)
# Image import panel
_import_browser = Str
_import_file_btn = Button(
"File(s)",
tooltip="Select a file to import, typically a multiplane image.\n"
"Channels are determined by names ending with '_ch_x'\n"
"(eg 'img_ch_0.tif', 'img_ch_1.tif'). If only one file is\n"
"selected, all files with matching names except for the\n"
"channel will also be added.")
_import_dir_btn = Button(
"Dir",
tooltip="Select a directory of single-plane images to import.\n"
"Files will be sorted alphabetically, and files ending with\n"
"'_ch_x' are sorted into the given channel. Any file that\n"
"cannot be loaded will be simply ignored.")
_import_table = TabularEditor(
adapter=ImportFilesArrayAdapter(), editable=True, auto_resize_rows=True,
stretch_last_section=False)
_import_paths = List # import paths table list
_import_btn = Button("Import files")
_import_btn_enabled = Bool
_import_clear_btn = Button("Clear import")
_import_res = Array(float, shape=(1, 3))
_import_mag = Float(1.0)
_import_zoom = Float(1.0)
_import_shape = Array(int, shape=(1, 5), editor=ArrayEditor(
width=-40, format_str="%0d"))
# map bits to bytes for constructing Numpy data type
_IMPORT_BITS = OrderedDict((
("Bit", ""), ("8", "1"), ("16", "2"), ("32", "3"), ("64", "4")))
_import_bit = List
# map numerical signage and precision to Numpy data type
_IMPORT_DATA_TYPES = OrderedDict((
("Type", ""),
("Unsigned integer", "u"),
("Signed integer", "i"),
("Floating point", "f"),
))
_import_data_type = List
# map byte order name to Numpy symbol
_IMPORT_BYTE_ORDERS = OrderedDict((
("Default order", "="), ("Little endian", "<"), ("Big endian", ">")))
_import_byte_order = List
_import_prefix = Str
_import_feedback = Str
# BrainGlobe panel
_bg_atlases = List
_bg_atlases_sel = List
_bg_atlases_table = TabularEditor(
adapter=BrainGlobeArrayAdapter(), editable=False, auto_resize_rows=True,
stretch_last_section=False, selected="_bg_atlases_sel")
_bg_access_btn = Button("Open")
_bg_remove_btn = Button("Remove")
_bg_feedback = Str
# Image viewers
atlas_eds = [] # open atlas editors
flipz = True # True to invert 3D vis along z-axis
controls_created = Bool(False)
mpl_fig_active = Any
scene = None if MlabSceneModel is None else Instance(MlabSceneModel, ())
scene_3d_shown = False # 3D Mayavi display shown
selected_viewer_tab = vis_handler.ViewerTabs.ROI_ED
select_controls_tab = Int(-1)
# Viewer options
_check_list_3d = List(
tooltip="Raw: show raw intensity image; limit region to ROI\n"
"Surface: render as surface; uncheck to render as points\n"
"Clear: clear scene before drawing new objects\n"
"Panes: show back and top panes\n"
"Shadows: show blob shadows as circles")
_check_list_2d = List(
tooltip="Filtered: show filtered image after detection in ROI planes\n"
"Border: margin around ROI planes\n"
"Seg: segment blobs during detection in ROI planes\n"
"Grid: overlay a grid in ROI planes\n"
"MIP: maximum intensity projection in overview images")
_DEFAULTS_2D = [
"Filtered", "Border", "Seg", "Grid", "MIP"]
_planes_2d = List
_border_on = False # remembers last border selection
_DEFAULT_BORDER = np.zeros(3) # default ROI border size
_DEFAULTS_PLANES_2D = ["xy", "xz", "yz"]
_circles_2d = List # ROI editor circle styles
_styles_2d = List
_atlas_ed_options = List(
tooltip="Labels: show a description when hovering over an atlas label"
"in\nboth the ROI and Atlas Editors\n"
"Sync ROI: move to the ROI offset whenever it changes\n"
"Zoom ROI: zoom into ROI; select Center to center ROI on "
"crosshairs\n"
"Crosslines: show lines for orthogonal planes")
_atlas_ed_options_prev = [] # last atlas ed option settings
#: Choices of planes to show in Plot Editors.
_PLOT_ED_PLANES: Sequence[str] = ("", "xy", "xz", "yz")
_atlas_ed_plot_tip = (
"Plane to show in the {} plot. The blank selection will turn off the\n"
"plot and expand the other plots to fill the space.")
_atlas_ed_plot_left = List(tooltip=_atlas_ed_plot_tip.format("left"))
_atlas_ed_plot_right_up = List(
tooltip=_atlas_ed_plot_tip.format("upper right"))
_atlas_ed_plot_right_down = List(
tooltip=_atlas_ed_plot_tip.format("lower right"))
_atlas_ed_plot_ignore = False
# atlas labels
_atlas_label = None
_structure_scale_low = -1
_structure_scale_high = 20
_structure_scale = Int(_structure_scale_high) # ontology structure levels
_structure_remap_btn = Button(
"Remap",
tooltip="Remap atlas labels to this level")
_region_name = Str(
tooltip="Navigate to selected region. Start typing to search.")
_region_names = Instance(TraitsList)
# tooltip for both text box and options since options group has no main
# label to display a tooltip
_region_id = Str(
tooltip="IDs: IDs of labels to navigate to. Add +/- to including both\n"
"sides. Separate multiple IDs by commas. To also show loaded\n"
"blobs, check the blob channels in the \"Detect\" panel.\n\n"
"Both sides: include correspondings labels from opposite sides"
"\nChildren: include all children of the label\n"
"Append: append selected region\n"
"Show all: show abbreviations for all visible labels")
_region_options = List
_mlab_title = None
_circles_opened_type = None # enum of circle style for opened 2D plots
_opened_window_style = None # 2D plots window style curr open
_img_region = None
_PREFIX_BOTH_SIDES = "+/-"
_camera_pos = None
_roi_ed_fig = Instance(figure.Figure, ())
_atlas_ed_fig = Instance(figure.Figure, ())
# Status bar
_status_bar_msg = Str() # text for status bar
_prog_pct = Int(0) # progress bar percentage
_prog_pct_max = Int(100) # progress bar max percentage
_prog_msg = Str() # progress bar message
# ROI selector panel
panel_roi_selector = VGroup(
VGroup(
HGroup(
Item("_filename", label="Image path", style="simple"),
Item("_filename_btn", show_label=False),
),
HGroup(
Item("_channel", label="Channels", style="custom",
enabled_when="not _rgb",
editor=CheckListEditor(
name="object._channel_names.selections", cols=8)),
Item("_rgb", label="RGB",
enabled_when="_rgb_enabled and not _merge_chls"),
Item("_merge_chls", label="Merge", enabled_when="not _rgb"),
),
),
VGroup(
HGroup(
Item("_main_img_name_avail", label="Intensity", springy=True,
editor=CheckListEditor(
name="object._main_img_names_avail.selections",
format_func=lambda x: x)),
Item("_main_img_name", show_label=False, springy=True,
editor=CheckListEditor(
name="object._main_img_names.selections",
format_func=lambda x: x)),
Item("_reload_btn", show_label=False),
),
HGroup(
Item("_labels_img_name", label="Labels", springy=True,
editor=CheckListEditor(
name="object._labels_img_names.selections",
format_func=lambda x: x)),
Item("_labels_ref_path", label="Reference", style="simple"),
Item("_labels_ref_btn", show_label=False),
),
label="Registered Images",
),
VGroup(
HGroup(
Item("rois_check_list", show_label=False,
editor=CheckListEditor(
name="object._rois_selections.selections")),
label="Regions",
),
HGroup(
Item("roi_array", label="Size (x,y,z)"),
Item("_roi_center", label="Center",
editor=BooleanEditor()),
),
Item("x_offset",
editor=RangeEditor(
low_name="x_low",
high_name="x_high",
mode="slider")),
Item("y_offset",
editor=RangeEditor(
low_name="y_low",
high_name="y_high",
mode="slider")),
Item("z_offset",
editor=RangeEditor(
low_name="z_low",
high_name="z_high",
mode="slider")),
),
VGroup(
VGroup(
Item("_check_list_2d", style="custom", label="ROI Editor",
editor=CheckListEditor(
values=_DEFAULTS_2D, cols=5, format_func=lambda x: x)),
HGroup(
Item("_circles_2d", style="simple", show_label=False,
editor=CheckListEditor(
values=[e.value for e in
roi_editor.ROIEditor.CircleStyles],
format_func=lambda x: x)),
Item("_planes_2d", style="simple", show_label=False,
editor=CheckListEditor(
values=_DEFAULTS_PLANES_2D,
format_func=lambda x: "Plane {}".format(x.upper()))),
Item("_styles_2d", style="simple", show_label=False,
springy=True,
editor=CheckListEditor(
values=[e.value for e in Styles2D],
format_func=lambda x: x)),
),
show_border=True,
),
VGroup(
HGroup(
Item("_atlas_ed_options", style="custom", label="Atlas Editor",
editor=CheckListEditor(
values=[e.value for e in AtlasEditorOptions],
cols=len(AtlasEditorOptions),
format_func=lambda x: x)),
),
HGroup(
Item("_atlas_ed_plot_left", style="simple", label="Left plane",
editor=CheckListEditor(
values=_PLOT_ED_PLANES, format_func=lambda x: x)),
Item("_atlas_ed_plot_right_up", style="simple",
label="Upper right",
editor=CheckListEditor(
values=_PLOT_ED_PLANES, format_func=lambda x: x)),
Item("_atlas_ed_plot_right_down", style="simple",
label="Lower right",
editor=CheckListEditor(
values=_PLOT_ED_PLANES, format_func=lambda x: x)),
),
show_border=True,
),
VGroup(
Item("_check_list_3d", style="custom", label="3D Viewer",
editor=CheckListEditor(
values=[e.value for e in Vis3dOptions],
cols=len(Vis3dOptions), format_func=lambda x: x)),
show_border=True,
),
),
# give initial focus to text editor that does not trigger any events to
# avoid inadvertent actions by the user when the window first displays;
# set width to any small val to get smallest size for the whole panel
Item("_roi_feedback", style="custom", show_label=False, has_focus=True,
width=100),
# generate progress bar but give essentially no height since it will
# be moved to the status bar in the handler
Item("_prog_pct", show_label=False, height=-2,
editor=ProgressEditor(min=0, max_name="_prog_pct_max")),
HGroup(
Item("btn_redraw", show_label=False),
Item("_btn_save_fig", show_label=False),
Item("_roi_btn_help", show_label=False),
),
label="ROI",
)
# blob detections panel
panel_detect = VGroup(
HGroup(
Item("btn_detect", show_label=False),
Item("_segs_chls", label="Chl", style="custom",
editor=CheckListEditor(
name="object._segs_chls_names.selections", cols=8)),
),
HGroup(
Item("btn_save_segments", show_label=False),
Item("_segs_labels", label="Change labels to",
editor=CheckListEditor(
values=[str(c) for c in
roi_editor.DraggableCircle.BLOB_COLORS.keys()],
format_func=lambda x: x)),
Item("_btn_verifier", show_label=False),
),
HGroup(
Item("_segs_model_path", label="Classifier model", style="simple"),
Item("_segs_model_btn", show_label=False),
),
HGroup(
Item("_segs_visible", style="custom", show_label=False,
editor=CheckListEditor(
values=[e.value for e in BlobsVisibilityOptions],
cols=len(BlobsVisibilityOptions),
format_func=lambda x: x)),
Item("_colocalize", label="Co-localize by",
editor=CheckListEditor(
values=[e.value for e in ColocalizeOptions],
format_func=lambda x: x)),
Item("_blob_color_style", show_label=False, springy=True,
editor=CheckListEditor(
values=[e.value for e in BlobColorStyles],
format_func=lambda x: x)),
),
Item("scale_detections", label="Scale 3D blobs",
editor=RangeEditor(
low_name="_scale_detections_low",
high_name="_scale_detections_high",
mode="slider", format_str="%.3g")),
Item("_segs_mask", label="3D blobs mask size",
editor=RangeEditor(
low_name="_segs_mask_low",
high_name="_segs_mask_high",
mode="slider")),
VGroup(
Item("_segments", editor=segs_table, show_label=False),
Item("segs_feedback", style="custom", show_label=False),
),
label="Detect",
)
# profiles panel
panel_profiles = VGroup(
# profile selectors
VGroup(
HGroup(
Item("_profiles_cats", style="simple", show_label=False,
editor=CheckListEditor(
values=[e.value for e in ProfileCats], cols=1,
format_func=lambda x: x)),
Item("_profiles_chls", label="Chls", style="custom",
editor=CheckListEditor(
name="object._channel_names.selections", cols=8)),
),
HGroup(
Item("_profiles_name", show_label=False,
editor=CheckListEditor(
name="object._profiles_names.selections",
format_func=lambda x: x)),
Item("_profiles_add_btn", show_label=False),
Item("_profiles_load_btn", show_label=False),
),
label="Profile Selection",
),
# selected profile preview and table of profiles
VGroup(
# neg height to ignore optimal height
Item("_profiles_preview", style="custom", show_label=False,
height=-100),
Item("_profiles", editor=_profiles_table, show_label=False),
label="Profile Preview",
),
# combined profiles dict
VGroup(
Item("_profiles_combined", style="custom", show_label=False),
label="Combined profiles",
),
# settings/preferences
VGroup(
HGroup(
Item("_profiles_ver", style="readonly",
label="MagellanMapper version:"),
),
HGroup(
Item("_profiles_reset_prefs_btn", show_label=False),
Item("_profiles_btn_help", show_label=False),
),
label="Settings",
),
label="Profiles",
)
# image adjustment panel
panel_imgadj = VGroup(
HGroup(
Item("_imgadj_name", label="Image",
editor=CheckListEditor(
name="object._imgadj_names.selections")),
# use EnumEditor for radio buttons
Item("_imgadj_chls", label="Channel", style="custom",
editor=EnumEditor(
name="object._imgadj_chls_names.selections", cols=8)),
),
# channel colormap selector
Item("_imgadj_color_name", label="Color",
editor=EnumEditor(
name="object._imgadj_color_names.selections",
completion_mode="popup", evaluate=True)),
# use large range sliders to adjust min/max range and brightness
HGroup(
Item("_imgadj_min", label="Min", editor=RangeEditor(
low_name="_imgadj_min_low", high_name="_imgadj_min_high",
mode="xslider", format_str="%.1g")),
Item("_imgadj_min_auto", label="Auto", editor=BooleanEditor()),
),
HGroup(
Item("_imgadj_max", label="Max", editor=RangeEditor(
low_name="_imgadj_max_low", high_name="_imgadj_max_high",
mode="xslider", format_str="%.1g")),
Item("_imgadj_max_auto", label="Auto", editor=BooleanEditor()),
),
HGroup(
Item("_imgadj_brightness", label="Brightness", editor=RangeEditor(
low_name="_imgadj_brightness_low",
high_name="_imgadj_brightness_high", mode="xslider",
format_str="%.1g"))
),
HGroup(
Item("_imgadj_contrast", label="Contrast", editor=RangeEditor(
low=0.0, high=2.0, mode="slider", format_str="%.1g")),
),
HGroup(
Item("_imgadj_alpha", label="Opacity", editor=RangeEditor(
low=0.0, high=1.0, mode="slider", format_str="%.1g")),
),
HGroup(
# alpha blending controls
Item("_imgadj_alpha_blend_check", label="Blend",
enabled_when="not _merge_chls"),
Item("_imgadj_alpha_blend", show_label=False, editor=RangeEditor(
low=0.0, high=1.0, mode="slider", format_str="%.1g"),
enabled_when="_imgadj_alpha_blend_check"),
),
label="Adjust Image",
)
# import panel
panel_import = VGroup(
VGroup(
Item("_import_file_btn", label="Multiplane file(s) to import"),
Item("_import_dir_btn", label="Directory of single-plane images"),
label="Import File Selection"
),
VGroup(
Item("_import_paths", editor=_import_table, show_label=False),
),
VGroup(
Item("_import_res", label="Resolutions (x,y,z)", format_str="%.4g"),
HGroup(
Item("_import_mag", label="Objective magnification"),
Item("_import_zoom", label="Zoom"),
),
label="Microscope Metadata",
),
VGroup(
Item("_import_shape", label="Shape (chl, x, y, z, time)"),
HGroup(
Item("_import_prefix", style="simple", label="Path"),
),
HGroup(
Item("_import_bit", style="simple", label="Data Bit",
editor=CheckListEditor(
values=tuple(_IMPORT_BITS.keys()), cols=1)),
Item("_import_data_type", style="simple", show_label=False,
editor=CheckListEditor(
values=tuple(_IMPORT_DATA_TYPES.keys()), cols=1)),
Item("_import_byte_order", style="simple", show_label=False,
editor=CheckListEditor(
values=tuple(_IMPORT_BYTE_ORDERS.keys()), cols=1)),
),
label="Output image file"
),
HGroup(
Item("_import_btn", show_label=False,
enabled_when="_import_btn_enabled"),
Item("_import_clear_btn", show_label=False),
),
Item("_import_feedback", style="custom", show_label=False),
label="Import",
)
# BrainGlobe panel
panel_brain_globe = VGroup(
Item("_region_name", label="Region",
editor=EnumEditor(
name="object._region_names.selections",
completion_mode="popup", evaluate=True)),
HGroup(
Item("_region_id", label="IDs",
editor=TextEditor(
auto_set=False, enter_set=True, evaluate=str)),
Item("_region_options", style="custom", show_label=False,
editor=CheckListEditor(
values=[e.value for e in RegionOptions],
cols=len(RegionOptions), format_func=lambda x: x)),
),
HGroup(
Item("_structure_scale", label="Atlas level",
editor=RangeEditor(
low_name="_structure_scale_low",
high_name="_structure_scale_high",
mode="slider")),
Item("_structure_remap_btn", show_label=False),
),
VGroup(
Item("_bg_atlases", editor=_bg_atlases_table, show_label=False),
label="BrainGlobe Atlases"
),
HGroup(
Item("_bg_access_btn", show_label=False),
Item("_bg_remove_btn", show_label=False),
),
Item("_bg_feedback", style="custom", show_label=False),
label="Atlases",
)
# tabbed panel of options
panel_options = Tabbed(
panel_roi_selector,